0

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>

2 Answers2

0

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

Community
  • 1
  • 1
Nalin Aggarwal
  • 886
  • 5
  • 8
-2

Just change your P tags into SPAN and it's working:

jQuery("span").find('span').each(function() {
    jQuery(this).css("color", "green");
});

Here is working demo https://jsfiddle.net/0gqL9q3c/