Heading inside paragraph selector not working

Viewed 70

I want to change the background color of all the children of the <p> tag to GREEN. But the code I have written doesn't work. But if I change the <p> tag to <div> it's working. But I need it to work on the <p> tag using jQuery Advanced Selectors

Code:

$(document).ready(() => {
  //Change background color of children to green
  //Below code is not working
  $("#intro").children().each(function() {
    $(this).css("background-color", "green");
  });
  //Show only first 2 list item
  $('ol li').hide().slice(0, 2).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
  <h6>The purpose of jQuery is to make it much easier to use JavaScript on your website</h6>
</p>
<ol>
  <li>HTML/DOM manipulation</li>
  <li>CSS manipulation</li>
  <li>Effects and animations</li>
  <li>AJAX</li>
</ol>

1 Answers

h is not a valid child of p

Paragraph P

Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing </p> tag.

Permitted content: Phrasing content

The rendered HTML becomes

<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
</p><!-- inserted by browser -->
<h6>The purpose of jQuery is to make it much easier to use JavaScript on your website</h6>
<p><!-- inserted by browser -->
</p>

You can do this:

$(document).ready(() => {
  //Change background color of children to green
  //Below code is now working
  $("#intro").children().each(function() {
    $(this).css("background-color", "green");
    $('<br />').insertBefore(this); // because of the inline-block
  });
  //Show only first 2 list item
  $('ol li').hide().slice(0, 2).show();
})
.h6 { 
    display: inline-block;
    font-size: .67em;
    margin-top: 2.33em;
    margin-bottom: 2.33em;
    margin-left: 0;
    margin-right: 0;
    font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<p id="intro">jQuery is a lightweight, "write less, do more" JavaScript library.
  <span class="h6">The purpose of jQuery is to make it much easier to use JavaScript on your website</span>
</p>
<ol>
  <li>HTML/DOM manipulation</li>
  <li>CSS manipulation</li>
  <li>Effects and animations</li>
  <li>AJAX</li>
</ol>

Related