【问题标题】:jQuery's contents() methods in pure JS纯 JS 中 jQuery 的 contents() 方法
【发布时间】:2020-07-20 15:38:05
【问题描述】:

所以我一直在尝试在不导入 jQuery 库的情况下执行以下代码:

$(".parent-class").contents().find(".child-class").css("color", "red");

我知道 .contents() 从 jQuery 文档中获取匹配元素集中每个元素的子元素,包括文本和注释节点,但我不知道我想我明白那个描述是什么意思。我尝试让.parent-class 的孩子使用:

let theChildren = document.querySelector('.parent-class').children;

但这与.contents().find(".child-class") 的作用不同。

编辑:根据 cmets 的要求,我创建了一个 new question,因为这个似乎不够具体。

【问题讨论】:

  • contents() 主要用于 jQuery 中需要选择文本节点时。在第一个代码示例中,您根本不需要它,因为您使用 find() 选择具有类的元素。
  • @RoryMcCrossan 我尝试在原始代码中省略 content() 方法,但这会破坏功能。我正在尝试编辑嵌入式 Twitter 提要的样式,我只能通过使用以下 sn-p $(".twitter-timeline").find(".timeline-Tweet-text").css("margin-bottom", "-10px"); 获取模块的子节点来做到这一点
  • 在这种情况下,您最好针对具体问题提出一个新问题,而不是对contents() 的目的提出一般性问题
  • 我将编辑问题以更好地适应具体问题。
  • 你应该开始一个新问题,因为你现在有了这个问题的答案

标签: javascript jquery pure-js


【解决方案1】:

contents() 主要用于 jQuery 中需要选择文本节点时。在第一个代码示例中,您根本不需要它,因为您使用find() 选择具有类的元素。这些 jQuery 行将起到相同的作用:

$(".parent-class").find(".child-class").css("color", "red");
$(".parent-class .child-class").css("color", "red");

在普通的 JS 中,这将是:

document.querySelectorAll('.parent-class .child-class').forEach(el => el.style.color = 'red');

请注意querySelectorAll()。这将返回一个 nodeList ,您需要像 jQuery 代码一样迭代更新样式。

没有明确的 JS 等效于 contents(),因为您手动遍历以查找要定位的节点,或使用 querySelector()getElementByX() 等定位元素。

【讨论】:

    【解决方案2】:

    这将获得第一个父类中的第一个子类:

    let theChildren = document.querySelector('.parent-class .child-class');
    

    这将获取每个父类中的所有子类:

    let theChildren = document.querySelectorAll('.parent-class .child-class');
    

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2012-10-31
      • 2014-03-03
      • 2011-06-24
      相关资源
      最近更新 更多