I want to test if an element has a specific class on it. This if
statement works:
if (children[i].className === siblingClass)
However, it only works if children[i]
has only one class, and it is exactly the same as the value of siblingClass
. I want to make the function a little more generalized, to test if children[i]
has siblingClass
even if it also has other classes as well.
So I tried the classList.contains function, like this:
if (children[i].classList.contains(siblingClass))
But, when I try it (in Chrome), the console log says:
Uncaught TypeError: Cannot read property 'contains' of undefined
How do I create a test to see if children[i]
has siblingClass
listed among one or more classes it may have?
Please note I would prefer to have a pure Javascript solution that does not require jQuery if possible.
This is the full function where the if
statement appears:
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;
}
This function is called from within other functions when I want to search among element siblings for an element that has a specified class. It gets the parent of the current element, loops through all children, and returns the first match. Or, at least that's the idea.
Here is some HTML which calls a function which in turn calls the above function:
<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>
copySiblingDataByClass()
would in turn call getSiblingByClass()
, and pass itself and the name of the class to be selected.