Reputation: 37
I have a javascript that uses document.querySelector() to retrieve text content from div/span elements - these are dynamically loaded. For example, user name is always available in the DOM. When the user comes online, an additional span is created indicating the IP address from which he is currently logged in; it disappears as soon as the user logs out.
So when the IP location element is not available in DOM, the console.log is not printing anything -
function f(){
try{ b=document.querySelector("#main > header > div>div>span").textContent,
name=document.querySelectorAll("#main > header > div>div>div>span")[1].textContent
}catch(e){return}
console.log(name + ", " + b)}
interval=setInterval(f,1000);
I want to capture each time the user logs in, and triggers the IP location element to display; or I want to write the if condition that checks whether the IP location span has been created in the DOM or not. Please note, the script also runs setInterval() to check when the user is online.
Upvotes: 0
Views: 1788
Reputation: 4578
You can use MutationObserver to check for changes in a node.
Here's an example:
const divObservable = document.getElementById('observable');
const btnAdd = document.getElementById('btn-add');
const btnRemove = document.getElementById('btn-remove');
btnAdd.addEventListener('click', () => {
setTimeout(() => {
divObservable.innerHTML = `<span>Hello, World!</span>`;
}, 2000);
});
btnRemove.addEventListener('click', () => {
setTimeout(() => {
divObservable.innerHTML = '';
}, 2000);
});
const observerConfig = {
attributes: true,
childList: true,
subtree: true,
};
const observerCallback = (mutationsList, observer) => {
for (var mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
}
};
const observer = new MutationObserver(observerCallback);
observer.observe(divObservable, observerConfig);
console.log('observing');
<div id="observable"></div>
<button id="btn-add">Async Add Span</button>
<button id="btn-remove">Async Remove Span</button>
Just check in the childList
mutation if the IP location exists or not.
Upvotes: 1
Reputation: 37
Since I am using setInterval in my script, I made further use of it in this scenario by checking the childElementCount -
target=document.getElementsByClassName("_3V5x5")[0].childElementCount;
if(target===2){
//IP location may be available now
} else {
// User is offline
}
Upvotes: 0