I have the following HTML and jQuery code:
<div id="outer">
<p>
<p>paragraph inside division.</p>
<h2>a heading</h2>
<ul>
<li>first item</li>
<li>second item</li>
</ul>
</p>
</div>
jQuery:
$(function() {
$divChildren = $('div#outer').children();
$divChildren.each(function(){
$(this).css('background-color', 'red');
});
alert($divChildren.length);
});
From what I see, the no. of immediate children that <div id="outer"> has should be 1, but jQuery sees 4. Why is that?
However, if everyting inside ‘#outer’ was wrapped in another div (instead of <p>), then it sees only 1 immediate child (as expected).
EDIT: This is definitely a malformed HTML nesting issue (and thanks everyone for answering). But my question should, more appropriately, have been: Is jQuery aware of and imposes HTML nesting rules or is it the browser’s construction of DOM tree (which imposes nesting rules) and jQuery simply returns what is sees in DOM tree?
your html code is invalid. you cannot put
ptag insideptagThe paragraph element can be contained inside the elements “address”, “applet”, “blockquote”, “body”, “button”, “center”, “del”, “dd”, “div”, “fieldset”, “form”, “iframe”, “ins”, “li”, “map”, “noframes”, “noscript”, “object”, “td”, and “th”.
HTML inline elements are the only elements that may be contained within a paragraph element.
in HTML.