Search code examples
jqueryjquery-selectorsnestedparagraphs

jQuery selector of nested <p>


Who knows why in the world this will not work:

$( "p  p" ).each(function() {
    $(this).css("color", "green");
});

as well as "p > p", or anything with nested paragraph elements. While it is okay with div's and other elements

check this for example:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<script>
  alert('length='+$('p p').length); // 0
</script>

<div style="border:1px solid;">
  <p>The first paragraph in  div.</p>
  <p>The second paragraph in div (and the 2nd child in this div).</p>
  <p>
    <span>Span within p (WILL BE fount as "p > span")</span>
    <p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p > span")</span>
    <p>P within p (2).</p>
  </p>
</div>
<p>
    <span>Span within p (WILL BE fount as "p > span")</span>
    <p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p > span")</span>


Solution

  • If you going and check the rendered html in the debugging tool, you gonna find that, none of your <p> element,that you were nesting is not nested anymore. They are rendered as a separate element. So I the html renders and you going to manipulate the DOM with $('p p') or $('p>p'), there is no element existing with the above specified syntax of expression or DOM manipulation.

    <div style="border:1px solid;">
      <p>The first paragraph in  div.</p>
      <p>The second paragraph in div (and the 2nd child in this div).</p>
      <p>
        <span>Span within p (WILL BE fount as "p &gt; span")</span>
        </p><p>P within p (1).</p> 
        <span>Span within p (will NOT be fount as "p &gt; span")</span>
        <p>P within p (2).</p>
      <p></p>
    </div>
    <p>
        <span>Span within p (WILL BE fount as "p &gt; span")</span>
        </p><p>P within p (1).</p> 
        <span>Span within p (will NOT be fount as "p &gt; span")</span>
    

    As mentioned by @Ish and @j08691 that <p> tag cannot be nested , you are able to see clearly in your browser with the help of debugging tool of the browser. For More reffernce, Please check another SO answer on it