Reputation:
If I have some ".blocks"
body
section
.main-container
.container
.block
.blcok
And I need add className for all parents block, div, section, body.
When I use jquwry I wrote like this:
$(".block").parents().addClass('block-wrapp');
But now I must use native js.
window.onload = function() {
let block = document.getElementsByClassName('block');
for( let i = 0; i < block.length; i++ ) {
block[i].parentNode.classList.add('block-wrapp');
}
};
I try use
let mainBlock = block[i].parentNode.className;
console.log(mainBlock.parentNode);
But it doesn't work
Upvotes: 2
Views: 1040
Reputation: 392
Loop through all parents with a while
statement:
// loop through selected elements
for( let i = 0; i < block.length; i++ ) {
// get current looped element
let node = block[i];
// do this as long as we have a parent to go to
while (let parent = node.parentNode) {
// add class on parent
parent.classList.add('block-wrapp');
// move up the tree
node = parent;
}
}
You can improve a bit the performance so you don't visit the same parents and traverse the entire tree over and over again for sibling elements. For this, get a list of processed parents and skip them the next time you encounter them:
let visitedParents = [];
while (parent = node.parentNode && visitedParents.indexOf(parent) === -1) {
// ...
// mark this parent as visited
visitedParents.push(parent);
}
Finally, you should also stop when reaching the body
element, otherwise you'll reach html
and the document
, which I presume you don't want to:
while (node.parentNode !== document.body && .... ) { ... }
Upvotes: 1