【问题标题】:get text except a particular class or id in jquery在 jquery 中获取除特定类或 id 之外的文本
【发布时间】:2021-07-20 15:18:44
【问题描述】:

我想从 html div 中提取文本。

<div id="example">
  I am posting a <span class='outer'>a new question <span class='inner'>in stackoverflow</span></span>
</div>

const text = $("#example")
              .clone()
              .children()
              .removeClass("inner")
              .end()
              .text();

text 我收到I am posting a new question in stackoverflow。 但我希望输出为I am posting a new question。 我不想要内部跨度。 任何人都可以在这里帮助我。谢谢:)

【问题讨论】:

  • 你是在移除类,而不是移除元素

标签: javascript html jquery text


【解决方案1】:

你很亲密。只是findremove 那个元素

const text = $("#example")
  .clone()
  .find('.inner')
  .remove()
  .end()
  .text();
console.log(text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="example">
  I am posting a <span class='outer'>a new question <span class='inner'>in stackoverflow</span></span>
</div>

【讨论】:

    【解决方案2】:

    试试这个:

    let clone = $("#example").clone();
    clone.find('.inner').remove();
    let text = clone.text();
    

    在您的示例中,您只是从元素中删除类,而不是元素本身。

    【讨论】:

      【解决方案3】:

      您需要删除元素,而不是删除类。

      const text = $("#example")
                    .clone()
                    .find(".inner")
                    .remove()
                    .end()
                    .text();
      
      
      console.log(text);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div id="example">
        I am posting a <span class='outer'>a new question <span class='inner'>in stackoverflow</span></span>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-04
        • 2012-05-10
        • 2019-04-21
        • 1970-01-01
        • 2018-09-25
        • 2019-08-01
        • 2015-08-06
        • 1970-01-01
        相关资源
        最近更新 更多