I am using MutationObserver to listen for any element added in the dom. After the element(s) is added, I want to check whether the element(s) had the computer style cursor to be pointer or not. But I am not sure how to approach this problem as it returns the parent node added in the dom, it didn’t query each child of the parent node :-
function myfunc() {
const ele = document.createElement('div')
ele.innerHTML = `<span><a>I am added</a></span><h2><a>I am two</a></h2>`
document.body.appendChild(ele)
}
const observer = new MutationObserver(mutationsList => {
mutationsList.forEach(mutation => {
// Check if nodes were added
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// Iterate over added nodes
mutation.addedNodes.forEach(addedNode => {
// Check if added node is an element and not a script
if (
addedNode.nodeType === Node.ELEMENT_NODE &&
addedNode.tagName !== 'SCRIPT'
) {
const child = addedNode.childNodes;
if(child.length > 0) {
for (let i = 0; i < child.length; i++) {
console.log(child[i])
if(window.getComputedStyle(child[i]).cursor === 'pointer') {
console.log('This')
}
else {
console.log('No It didn')
}
}
}
}
});
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
a {
cursor: pointer;
}
<button onClick="myfunc()">
Add to DOM
</button>
2
Answers
First of all, I’d start by using a dedicated container div to push elements into instead of the body of the document.
Next you dont have to work with child list and instead (since you only add elements) can simply get the latest element added to the container (or body). Afterwards you get all anchor elements of that element by using lastElementChild. Now iterate over each anchor tag and compare the computed style with what you want.
The code you provided demonstrates the use of a MutationObserver to detect changes in the DOM, specifically when nodes are added. It then iterates over the added nodes and checks if any of the child nodes have a CSS style of cursor: pointer.
To get the specific CSS-styled element from the entire node, you can modify the code as follows:
In the updated code, after determining that the added node is an element, it uses querySelectorAll(‘*’) to select all descendant elements within that node. Then, it filters those elements based on their computed style, specifically checking if the cursor property is set to pointer. The resulting array contains the elements with a pointer cursor.
Note: This code will find all elements with a pointer cursor within the added node and its descendants. If you only want to check the added node itself, you can remove the querySelectorAll(‘*’) and replace addedNode with addedNode in the filtering step.