Make Function Wait Until Element Exists

How to wait until an element exists?

DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

let observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (!mutation.addedNodes) return

for (let i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
let node = mutation.addedNodes[i]
}
})
})

observer.observe(document.body, {
childList: true
, subtree: true
, attributes: false
, characterData: false
})

// stop watching using:
observer.disconnect()

JavaScript - wait until element loaded on website using Chrome extension

Can be done with MutationObserver:

function handleSomeDiv(someDiv) { 
console.log("div was handled");
}

const observer = new MutationObserver(function (mutations, mutationInstance) {
const someDiv = document.getElementById('some-div');
if (someDiv) {
handleSomeDiv(someDiv);
mutationInstance.disconnect();
}
});

observer.observe(document, {
childList: true,
subtree: true
});

Javascript: How to wait until an element exists in DOM

I am on a phone and can't check your code, but based on the details you gave, you need to capture the input bubble (since it's not possible to target a dynamically created button directly)

To do so, put your event handler on an element that already exists without user input, such as an upper div... when the user clicks the button the event will bubble up to that div and you can capture it there.

You said you're new to Javascript, so if you're unfamiliar with the concept Google search for "Javascript event bubbling" and there are plenty of great articles.

EDIT: I created a very basic example of this in action if you want to see, just save this as an HTML file and open in your browser.

<html>
<body>
<div>
<button id="addBtn">Add New Button</button>
</div>

<div id="newBtnContainer"></div>
</body>
</html>

document.getElementById('addBtn').onclick = function() {
var btn = document.createElement('button');
var btnText = document.createTextNode("Dynamically Created Button");
btn.appendChild(btnText);
document.getElementById('newBtnContainer').appendChild(btn);
}

document.getElementById('newBtnContainer').onclick = function() {
alert('Found the button!');
}

Hope this helps your use case
Thanks

How to wait until an element exists with JavaScript?

I finally made it with MutationObserverinterface in an easy way instead of with promises.

var handler = {    makeThings: 0,    otherStuff: 0};var globalHandler = new Proxy(handler, {    set: function(obj, prop, value) {        obj[prop] = value        if (prop == "makeThings") {            var observer = new MutationObserver(function(mutations) {                if ($("p").length) {                    console.log("Exist, lets do something");                    observer.disconnect();                }            });            // start observing            observer.observe(document.body, {                childList: true,                subtree: true            });        }        return true;    }});
$(document).ready(function() { $("button").on("click", function() { $("p").remove(); globalHandler.makeThings = 1; //This element comes with ajax but I use a setTimeout for this example setTimeout(function() { $("#newContent").append("<p>Ajax element</p>"); }, 2000); });});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><body>  <button>New content</button>  <div id="newContent"></div></body>

Wait until element exists, loop, then store in variable

As you are performing an asyncrhonous task, I'd suggest modifying your code to accept a callback, or return a promise. Here is a callback modification:

var i =1;
function waitForElClass(data, cb){
var element = data.selected;
var index = data.index;

var findEl = document.getElementsByClassName(element)[index];
console.log(i);
i++;
var to = window.setInterval(function(){
if($(findEl).length){
console.log(findEl);
cb(findEl);
window.clearInterval(to);
}
},500)
}

It could then be used as follows:

var data = {selected: 'new', index: 0};
var element;
waitForElClass(data, function(el) {
element = el;
//or something more meaningful here
});

Make promise wait until element NOT exists

If the parent of the element you want to check for is persistent, and the element you want to check for is removed from the parent (eg, the parent itself isn't removed), attach an observer to the parent and check to see if any of its removedNodes match the element you want to observe:

const prom = new Promise((resolve) => {  new MutationObserver((mutations, observer) => {    for (const mutation of mutations) {      for (const removedNode of mutation.removedNodes) {        if (removedNode.id === 'button') {          observer.disconnect();          resolve();        }      }    }  })    .observe(outer, { childList: true });});
button.addEventListener('click', () => button.remove());
prom.then(() => { console.log('promise resolved');});
<div id="outer">  <button id="button">click</button></div>


Related Topics



Leave a reply



Submit