如何在Javascript的if语句中成功地用classList代替className?

如何在Javascript的if语句中成功地用classList代替className?,javascript,Javascript,我想测试元素上是否有特定的类。此如果语句有效: if (children[i].className === siblingClass) 但是,只有当children[i]只有一个类,并且它与siblingClass的值完全相同时,它才起作用。我想让函数更一般化一点,测试children[I]是否有siblingClass,即使它也有其他类 所以我试着,像这样: if (children[i].classList.contains(siblingClass)) if (hasClass(chi

我想测试元素上是否有特定的类。此
如果
语句有效:

if (children[i].className === siblingClass)
但是,只有当
children[i]
只有一个类,并且它与
siblingClass
的值完全相同时,它才起作用。我想让函数更一般化一点,测试
children[I]
是否有
siblingClass
,即使它也有其他类

所以我试着,像这样:

if (children[i].classList.contains(siblingClass))
if (hasClass(children[i], siblingClass))
someNode.className.contains('foo'); // returns a boolean
但是,当我尝试(在Chrome中)时,控制台日志显示:

未捕获的TypeError:无法读取未定义的属性“contains”

如何创建一个测试,以查看
子类[I]
是否在其可能拥有的一个或多个类中列出了
同级类

请注意,如果可能的话,我希望有一个不需要jQuery的纯Javascript解决方案

这是出现
if
语句的完整函数:

function getSiblingByClass(currentObject, siblingClass)
{
    var parentofSelected = currentObject.parentNode,
        children = parentofSelected.childNodes,
        element,
        i;

    for (i = 0; i < children.length; i++)
    {
        if (children[i].classList.contains(siblingClass))
        {
            element = children[i];
            break;
        }
    }
    return element;
}
函数getSiblingByClass(currentObject,siblingClass) { var parentofselect=currentObject.parentNode, children=parentofSelected.childNodes, 元素, 我 对于(i=0;i
当我想在元素同级中搜索具有指定类的元素时,从其他函数中调用此函数。它获取当前元素的父元素,遍历所有子元素,并返回第一个匹配项。或者,至少是这样

下面是一些调用函数的HTML,该函数反过来调用上述函数:

   <div>
        <span class="fee">hello world</span>
        <span class="fi">Blah blah blah</span>
        <button class="foo" onclick="copySiblingDataByClass(this, 'fi');">Click here</button>
    </div>

你好,世界
废话废话
点击这里

CopySiblingDataCyclass()
将依次调用
getSiblingByClass()
,并传递自身和要选择的类的名称。

以下是一些可以尝试的方法:

var div=document.getElementById('div'); //类列表方法 if(div.classList.contains('world')) console.log(true); 其他的 console.log(false); //RegExp方法 if(/\s |^\wworld\s/.test(div.className)) console.log(true); 其他的 console.log(false); //将类名转换为数组以使用数组方法 if(div.className.split(“”).includes('world')) console.log(true); 其他的 console.log(false); //也使用数组方法,但更兼容 if(div.className.split(“”).indexOf('world')>-1) console.log(true); 其他的 console.log(false); //借用要在类列表上使用的数组方法 if(Array.prototype.includes.call(div.classList,'world')) console.log(true); 其他的 console.log(false)
<代码> <代码> 看来,您的代码是循环的<代码>的一部分,因此,请考虑以下内容:

var children=[].slice.call(document.getElementById('someID').childNodes);
var siblingClass = 'someClassName'; // for example

for(var i in children)
{
    if(!children.hasOwnProperty(i)){continue}; // get rid of "undefined"
    if(children[i].className.indexOf(siblingClass) > -1)
    {
        // you other code here 
    }
}

经过大量测试,并遵循这里的建议,我无法推断为什么
classList.contains()
对我不起作用。我正在运行版本60

然而,我需要将我的代码推进到产品中,所以我不能再花更多的时间来探究它的奥秘。幸运的是,我在中找到了一个函数,它将成功地从附加到对象的许多类中选择一个类

function hasClass(element, cls)
{
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
使用此函数,我的if语句现在如下所示:

if (children[i].classList.contains(siblingClass))
if (hasClass(children[i], siblingClass))
someNode.className.contains('foo'); // returns a boolean
。。。它工作得很好,所以这就是我将要使用的解决方案


如果有人能告诉我如何让
classList.contains()
工作,或者解释为什么不工作,我会很高兴地将答案标记为正确的。

在字符串或数组上使用
节点。contains
不是它的本意;利用你的功能,你可以让它那样工作

考虑以下“原型升级”——在JS代码的开头,它提供了全局功能:

Object.defineProperty(String.prototype,'contains',{enumerable:false, configurable:false, writable:false, value:function(find)
{
    return ((' '+this+' ').indexOf(' '+find+' ') > -1);
}});

现在,您可以在代码中的任意位置使用它,如下所示:

if (children[i].classList.contains(siblingClass))
if (hasClass(children[i], siblingClass))
someNode.className.contains('foo'); // returns a boolean

…然而,如果是我,我只会使用自动应用于所有元素的函数,如下所示:

Object.defineProperty(Element.prototype,'hasClass',{enumerable:false, configurable:false, writable:false, value:function(name)
{
    return ((' '+this.className+' ').indexOf(' '+name+' ') > -1);
}});

现在只需像这样使用它:

someNode.hasClass('foo');

什么是儿童[i]
?您使用的浏览器版本是什么?请创建一个@Satpal。错误清楚地表明定义了
children[i]
children[i]。classList
未定义的内容。如果
children[i]
undefined
,则错误将显示无法读取未定义的属性“classList”。这个问题很有可能是因为<代码>儿童[i] 不是一个元素节点@评论员:请善待OP不是白痴,你可能不知道上下文的确切细节——在得出结论和投票表决之前,这些假设的结果。@ TJ,如前所述,我正在测试的浏览器是Chrome。我已经按照您的要求添加了完整的功能。最新版本的chrome?您可能使用的版本不支持
类列表
,这就是为什么版本很重要谢谢您的响应。我在解析如何将
slice.call
hasOwnProperty
应用于我的用例时遇到了一点困难。我已经在我的问题中添加了完整的函数,希望它能使我的问题更加清晰。@question-the
[].slice.call()
部分只是一种确保处理“类似数组”结果的方法;因此,它只是将子节点转换/确保为可枚举列表。通过使用它,您现在还可以使用类似
childNodes.forEach(函数(节点){/*您的代码在这里*/})--那么您就不需要
拥有自己的属性了。