I\'m really struggling to see how to do this. I want to check if a class exsits somewhere in one of the parent elements of an element.
I don\'t want to use any libra
Another alternative for some those who like this style for modern/polyfilled browsers.
const hasClass = (element, className) => {
return element.classList.contains(className);
};
const hasParent = (element, className) => {
if (!element.parentNode) {
return false;
}
if (hasClass(element, className)) {
return true;
}
return hasParent(element.parentNode, className)
};
Working demo:
const hasClass = (element, className) => {
return element.classList.contains(className);
};
const hasParent = (element, className) => {
if (!element.parentNode) {
return false;
}
if (hasClass(element, className)) {
return true;
}
return hasParent(element.parentNode, className)
};
/* Demo Code, can ignore */
const child = document.getElementById('child');
const orphan = document.getElementById('orphan');
const output = document.getElementById('output');
const log = `child has parent? ${hasParent(child, 'list')}
orphan has parent? ${hasParent(orphan, 'list')}
`
output.innerText = log;
#output {
margin-top: 50px;
background: black;
color: red;
padding: 20px;
}