javascript - 段落选择器内的标题不起作用

标签 javascript html jquery css jquery-selectors

我想更改 <p> 的所有子项的背景颜色标记为绿色。但我写的代码不起作用。但如果我改变 <p>标记为<div>它正在工作。但我需要它来处理 <p>使用 jQuery 高级选择器标记

代码:

$(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>

最佳答案

h不是 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.

允许的内容:Phrasing content

渲染后的 HTML 变为

<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>

你可以这样做:

$(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>

关于javascript - 段落选择器内的标题不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62325945/

相关文章:

javascript - HTML/JS : Scroll to Top Visual Artifact

javascript - Bootstrap : Cancel data-toggle ="collapse" on nested button

javascript - insertbefore 并找到 css 类 - js 不工作

php - 多行验证

html - Xpath 选择除最后一项之外的项目包含语法

javascript - 异步提交表单以释放 UI

jquery - jcarousel ie7问题

javascript - 构建 Atom 包时,如何在弹出菜单中显示列表?

javascript - 如何正确压缩 Jquery 和大量插件?

javascript - Google map 标记的文本标签