如何使用 javascript 检查 HTMLCollection 是否包含具有给定类名的元素?

som*_*491 7 javascript

您好,我是编程新手,我想使用 javascript 访问对象内的数组...

我有如下的数据结构,

const some_obj = {
    accessKey: "",
    children: [
        div.someclassname,
        div.someclassname,
        div.someclassname.highlight,
    ]
}
Run Code Online (Sandbox Code Playgroud)

下面是我记录变量时在浏览器控制台中的样子。

object
current: div.wrapper
    accessKey: ""
    align: ""
    childElementCount: 4
    childNodes: NodeList(4) [div.someclassname, div.someclassname.highlight, 
    div.someclassname]
    children: HTMLCollection(4) [div.someclassname, 
    div.someclassname.highlight, div.someclassname]
Run Code Online (Sandbox Code Playgroud)

在控制台中打印 some_obj.children 会给出以下输出。object.children HTMLCollection(3) 0: div.someclassname 1: div.someclassname.highlight 2: div.someclassname

现在,我想从 some_obj 检查 some_obj 子数组中是否有 div.classname.highlight 。我该怎么做。

我尝试使用 some_obj.current.children.find() 但说 find 不是函数。

我如何检查 some_obj 子级是否具有 div.someclassname.highlight。有人可以帮我解决这个问题吗?谢谢

amb*_*ing 7

由于孩子们不是简单Array的而是HTMLCollection,所以应该关注的是:Array.from(NodeList)

假设我们想要查找某个元素div.someclassname.highlight是否存在children(测试类名someclassname& highlight)。

let childrenNodeArr = Array.from(some_obj.children);
/*or with spread operator [...some_obj.children]*/
/*each element is a dom node we can run classList.contains*/
const elemFound = childrenNodeArr.find(
  e =>
    e.classList.contains("someclassname") && e.classList.contains("highlight")
);

if (elemFound) {
  /*yes a div.someclassname.highlight*/
}
Run Code Online (Sandbox Code Playgroud)

注意:上面的测试将通过任何具有类名的 dom 元素someclassname,而highlight不仅仅是div. Element.classList.contains Array.from Array.find


sun*_*sen 4

我不\xe2\x80\x99t 认为有更优雅的解决方案HTMLCollection,但这可行。

\n\n
<!DOCTYPE html>\n<html lang="en">\n  <head>\n    <meta http-equiv="content-type" content="text/html; charset=utf-8">\n    <style>\n      .selected {\n        font-weight: bold;\n      }\n    </style>\n  </head>\n  <body>\n    <ul>\n      <li class="test">One</li>\n      <li class="test">two</li>\n      <li class="test selected">Three</li>\n    </ul>\n    <script>\n      var find = function(className) {\n        var elements = document.getElementsByClassName(\'test\');\n        var elementsArray = [].slice.call(elements);\n        for (var index = 0; index < elementsArray.length; index++) {\n          var element = elementsArray[index];\n          if (element.className.indexOf(className) !== -1) {\n            return true;\n            // return element; // If you wish to return the element instead of true (comment out previous line if this option is used)\n          }\n        }\n        return false;\n        // return null; // If you wish to return null instead of false (comment out previous line if this option is used)\n      }\n      console.log(find(\'selected\'));\n    </script>\n  </body>\n</html>\n
Run Code Online (Sandbox Code Playgroud)\n