【问题标题】:css don't select child elements [duplicate]css不选择子元素[重复]
【发布时间】:2016-03-13 15:45:47
【问题描述】:

假设我的 html 如下:

<h3 class="search-result-title">
            This is a test
            <small class="search-result-subtitle">
                Some more explanation
            </small>
        </h3>

如何在没有small 的情况下过滤文本This is a test

编辑:我将它与 symfony Dom Crawler 一起使用。

所以我有filter(a. h3 search-result-title); 但我不想要small 元素的内容。

【问题讨论】:

  • 这是一个 CSS 还是 jQuery 问题?
  • CSS 选择器只能选择元素(或伪元素)。不是文字。
  • 或者你也可以使用 jquery .html() 函数。api.jquery.com/html
  • 这是一个与 css 相关的问题。我在痛风爬虫中使用它。我根本不想要小元素及其内容

标签: jquery html domcrawler


【解决方案1】:

您可以使用此代码仅获取 h3 元素的文本。

document.querySelector('.search-result-title').firstChild.textContent

【讨论】:

    【解决方案2】:

    您可以使用filter() 提取内容,方法是将small 元素作为参数,然后提供remove() 它。

    $('.search-result-title').contents().filter("small").remove();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h3 class="search-result-title">
       This is a test
       <small class="search-result-subtitle">
          Some more explanation
       </small>
     </h3>

    【讨论】:

    • 知道如何将这项工作作为查找的一部分吗?即$topcols = $row.find('h4').contents().filter("small").remove(); 不起作用。
    • 不知道,斯蒂芬。经过大量谷歌搜索并抄袭其他 SO 答案后,我发布了此答案。
    • 不用担心,谢谢您的回复:)
    【解决方案3】:

    用 span 标签和用户 $('h3.search-result-title&gt;span:first-child') 包装 This is a test 以进行选择。

    【讨论】:

    • 我将它用于爬虫我无法更改 html
    • 所以你可以试试$('h3.search-result-title').firstChild.textContent
    【解决方案4】:

    我看到你在使用 jQUery,所以我发现了这个:text without child

    你可以这样做:

    $.fn.ignore = function(sel){ return this.clone().find(sel||">*").remove().end(); }; console.log($("h3.search-result-title").ignore("small").text().trim());

    这将返回“这是一个测试”

    希望对你有帮助!

    【讨论】:

      【解决方案5】:

      你可以使用.filter().contents()

      var txt = $('h3.search-result-title').contents().filter(function(){
          return this.nodeType == 3; 
       });
      

      【讨论】:

        猜你喜欢
        • 2011-05-12
        • 2016-03-31
        • 2016-07-28
        • 2016-12-15
        • 2023-01-13
        • 2013-12-13
        • 1970-01-01
        • 2013-06-04
        相关资源
        最近更新 更多