66.2k views
3 votes
Create a function that, given a DOM Element on the page, will visit the element itself and all of its descendents (not just its immediate children). For each element visited, the function should pass that element to a provided callback function.

The arguments to the function should be:

a DOM element
a callback function (that takes a DOM element as its argument)

User KamalDeep
by
7.8k points

1 Answer

2 votes

Final answer:

To create a function that visits a DOM element and all its descendants, use a recursive approach. Pass the initial DOM element to the function and use the 'childNodes' property to iterate through its children. Call the function recursively for each child node and apply the provided callback function.

Step-by-step explanation:

To create a function that visits a DOM element and all its descendants, you can use a recursive approach. First, you can pass the initial DOM element to the function. Then, in the function, you can use the 'childNodes' property to get all the child nodes of the element. For each child node, you can call the function recursively, passing the child node and the callback function as arguments.

Here's an example:

function visitElements(element, callback) {
callback(element);
var children = element.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType === 1) {
visitElements(children[i], callback);
}
}
}

// Usage:
var element = document.getElementById('myElement');

function myCallback(element) {
console.log(element);
}

visitElements(element, myCallback);
User Zhm
by
7.8k points