检查类是否存在于父级 - vanilla JS中

use*_*356 23 javascript dom

我真的很难看到如何做到这一点.我想检查一个类是否存在于元素的一个父元素中的某个地方.

我不想使用任何库,只需使用vanilla JS.

在下面的示例中,如果有问题的元素位于元素的子节点中,并且"the-class"作为类名,则它应返回true.

我认为jQuery会是这样的:

if( $('#the-element').parents().hasClass('the-class') ) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)

所以这返回true:

<div>
    <div class="the-class">
        <div id="the-element"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

这样做:

<div class="the-class">
    <div>
        <div id="the-element"></div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

...但是这会返回false:

<div>
    <div class="the-class">
    </div>
    <div id="the-element"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 36

你必须递归地做:

// returns true if the element or one of its parents has the class classname
function hasSomeParentTheClass(element, classname) {
    if (element.className.split(' ').indexOf(classname)>=0) return true;
    return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
}
Run Code Online (Sandbox Code Playgroud)

演示(打开控制台看true)

  • 如果som父母没有课程,则此操作将失败 (2认同)
  • 无法拆分未定义 (2认同)
  • 我使用此代码来处理没有类的元素:var hasSomeParentTheClass = function(element,classname){if(element.className &amp;&amp; element.className.split('').indexOf(classname)&gt; = 0)返回true;返回element.parentNode &amp;&amp; hasSomeParentTheClass(element.parentNode,classname); }` (2认同)
  • 使用“ parentElement”而不是“ parentNode”将避免此问题。 (2认同)
  • @lexa IE9不知道classList是什么. (2认同)

小智 25

您可以使用closest()的方法Element,直到找到所提供的selectorString匹配的节点的元素的横穿父母(朝文档根目录标题)。将返回自身或匹配的祖先。如果不存在这样的元素,则返回 null。

您可以将返回值转换为布尔值

const el = document.getElementById('div-03');

const r1 = el.closest("#div-02");  
console.log(Boolean(r1));
// returns the element with the id=div-02

const r2 = el.closest("#div-not-exists");
console.log(Boolean(r2));
Run Code Online (Sandbox Code Playgroud)
<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>
Run Code Online (Sandbox Code Playgroud)

  • 这就是您想要的答案,除非您仍然需要支持 MSIE 11 或更低版本。 (2认同)

Jam*_*ton 7

小提琴

代码

function hasClass(element, className) {
  var regex = new RegExp('\\b' + className + '\\b');
  do {
    if (regex.exec(element.className)) {
      return true;
    }
    element = element.parentNode;
  } while (element);
  return false;
}
Run Code Online (Sandbox Code Playgroud)

要么

function hasClass(element, className) {
  do {
    if (element.classList && element.classList.contains(className)) {
      return true;
    }
    element = element.parentNode;
  } while (element);
  return false;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我对Denys S\xc3\xa9guret发布的功能很满意,它看起来很优雅,我喜欢它。\n我只是稍微调整了该函数,因为如果参数中指定的类不存在于整个 DOM 中,则当递归到达文档对象时它会失败,因为我们控制元素是否具有父节点(在最后一行,当文档是元素时,父节点为空),但是在执行上一行之前,当元素是文档时,document.classNameundefined并且失败,因此必须将控件移动到顶部。

\n\n
function hasSomeParentTheClass(element, classname) {\n    //\n    // If we are here we didn\'t find the searched class in any parents node\n    //\n    if (!element.parentNode) return false;\n    //\n    // If the current node has the class return true, otherwise we will search\n    // it in the parent node\n    //\n    if (element.className.split(\' \').indexOf(classname)>=0) return true;\n    return hasSomeParentTheClass(element.parentNode, classname);\n}\n
Run Code Online (Sandbox Code Playgroud)\n


Fez*_*sta 5

您可以使用somecontains实现结果:

function hasParentWithMatchingSelector (target, selector) {
  return [...document.querySelectorAll(selector)].some(el =>
    el !== target && el.contains(target)
  )
}

// usage
hasParentWithMatchingSelector(myElement, '.some-class-name');
Run Code Online (Sandbox Code Playgroud)