【问题标题】:Select an element but not its child element using jquery使用jquery选择一个元素而不是它的子元素
【发布时间】:2021-06-20 15:00:36
【问题描述】:

我正在尝试更改 DIV 内所有 <p> 元素中的一些内容,但我不希望选择 <a> 标记或嵌套在 <p> 元素内的任何其他元素。这可行吗?

<div .main-div>
   <p> Select this sentence.......
      <a> Don't select this </a>
   </p>
   <p> Select this too....
      <a> Don't select this </a>
   </p>
</div>

我尝试了以下方法,但没有成功:

  1. var bodytext = $( '.main-div p').not('p &gt; a') ; //this selects the &lt;a&gt; tag as well
  2. var bodytext = $( '.site-inner p:visible').not('p:has(a)') ; //这不会选择两个

    ,因为它们都有标签。

如果有人可以提供建议,我将不胜感激。

提前致谢。

【问题讨论】:

  • 为什么不解释一下你真正追求的是什么?还有...&lt;div .main-div&gt;那是什么?

标签: jquery css dom jquery-selectors


【解决方案1】:

您不能使用 jQuery 直接访问文本节点。但是,您可以访问 jQuery 对象包含的底层元素的节点

$('.main-div p').each(function(i){
   const firstSentence = this.childNodes[0];
   firstSentence.textContent = 'Change #' +(i+1)  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-div">
   <p> Select this sentence.......
      <a> Don't select this </a>
   </p>
   <p> Select this too....
      <a> Don't select this </a>
   </p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多