【问题标题】:Equivalent of jQuery's contents().find() chained methods in pure JS等价于纯 JS 中 jQuery 的 contents().find() 链式方法
【发布时间】:2020-07-20 18:45:36
【问题描述】:

所以我一直在尝试在不使用 jQuery 的情况下执行以下代码:

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

我正在尝试编辑 嵌入式 Twitter 提要 的样式,而我只能通过使用这个 sn-p:$(".twitter-timeline").find(".timeline-Tweet-text").css("margin-bottom", "-10px"); 获取模块的子节点来做到这一点,无论出于何种原因。纯JS代码模仿这个功能是必要的。 我完整的js函数是:

// Change the style of the tweets after the module loads.
window.addEventListener('load', function () {
   $(".twitter-timeline").contents().find(".timeline-Tweet-text").css("margin-bottom", "-10px");
});

感谢您抽出宝贵时间阅读。

【问题讨论】:

  • $(selector1).contents().find(selector2) 不等同于(在大多数情况下,包括此处)$(selector1).find(selector2)?此外,它本身等同于(在许多情况下,包括此处)$(selector1 + " " + selector2)
  • 如果我删除了 contents() ,那么该功能就会出现问题。不知道为什么会这样。
  • 之前的question不是解决了你的问题吗?
  • 不,它没有。事实上,我在上一个问题中要求我在一个新问题中更详细地说明我需要什么。
  • 那么,您要匹配的实际 HTML 是什么?因为(除非我误读了文档).contents() 将提取第一级子代,.find() 搜索所有后代,所以从逻辑上讲,.contents().find() 应该搜索所有后代除了 直系子代。

标签: javascript jquery twitter twitter-feed pure-js


【解决方案1】:

您可以尝试以下方法:

document.querySelectorAll(".twitter-timeline .timeline-Tweet-text").forEach(function(el){
    el.style.marginBottom = "-10px";
 });

【讨论】:

  • 这与this的答案相同,OP说它No it did not解决了他的问题。
  • 这可能有点棘手,因为 Twitter 在其 HTML 代码中添加了如此多的动态内容。此外,它们使用背景图像 url 显示图像,而不是全部使用 标签。
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
相关资源
最近更新 更多