【问题标题】:Replicate .each() and $(this).find() with vanilla javascript使用香草 javascript 复制 .​​each() 和 $(this).find()
【发布时间】:2023-04-07 13:41:01
【问题描述】:

我想基本上做准确的下一个逻辑,但使用 vanilla javascript

$("li").each(function () {
    if (
        $(this).find("> .someClassName:nth-child(2)").length &&
        $(this).find("> .someClassName:last-child").length
    ) {
        $(this).addClass("className");
    }
});

我尝试了下一个逻辑,但它不起作用..

const selectedLIs = document.querySelectorAll("li");
selectedLIs.forEach(element => {
    if (
        element.querySelector("> .someClassName:nth-child(2)") && element.querySelector("> .someClassName:last-child")
    ) {
        element.classList.add("className");
    }
});

它给了我这个错误...

无法对“元素”执行“querySelector”:“> .someClassName:nth-child(2)' 不是有效的选择器。

那么我怎样才能只用 Javascript 来实现同样的事情呢?

【问题讨论】:

  • 我认为这是因为>。尝试删除它。
  • 你能在问题中包含 HTML 吗?
  • @guest271314 HTML是动态的,我基本上想选择
  • 的直接子元素。
  • @Ruby 将动态内容附加到document 后的 HTML 是什么?见stackoverflow.com/help/mcve
  • 标签: javascript foreach find each


    【解决方案1】:

    尝试从选择器中删除>

    element.querySelector(".someClassName:nth-child(2)") && element.querySelector(".someClassName:last-child")
    

    【讨论】:

    • 但是如何定位
    • 的目标子节点并检查它是否存在?
  • @Ruby,如果elementli,那么它应该返回选择器中的第一个匹配元素......
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签