Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different browser behavior regarding jQuery selector

Consider the following HTML5 code in body:

<p id="p1">
    Email: <input type="text" name="email" /><br />
    Name: <input type="text" name="name" /><br />
    <input type="submit" name="submit" value="Submit" />
</p>
<p id="p2">
    <form action="/index.php">
        Email: <input type="text" name="email" /><br />
        Name: <input type="text" name="name" /><br />
        <input type="submit" name="submit" value="Submit" />
    </form>
</p>

And the following javascript code:

$(document).ready(function() {
    alert("$(#p1 input).length: " + $("#p1 input").length + "\n$(#p2 input).length: " + $("#p2 input").length);
});​

Here are different browsers' outputs:

Internet Explorer 9.0.8112.16421

$(#p1 input).length: 3
$(#p2 input).length: 3

Chromium Version 20.0.1132.47 Ubuntu 12.04 (144678)

$(#p1 input).length: 3
$(#p2 input).length: 0

Mozilla Firefox for Ubuntu 17.0.1

$(#p1 input).length: 3
$(#p2 input).length: 0

Can anyone please explain why?

http://jsfiddle.net/LKStL/2/

like image 497
Mehran Avatar asked Dec 05 '25 06:12

Mehran


1 Answers

Elaborating on my comment:

Block elements like form aren't allowed inside p elements. It's invalid HTML, hence jQuery breaks trying to parse it. I can only speculate that maybe it works in Internet Explorer because Explorer doesn't follow HTML rendering standards (ie: it should break but doesn't).

Solution: Put your form tag outside of the p or change p to an element that allows block elements, like a div.

like image 160
Jan Avatar answered Dec 07 '25 20:12

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!