Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add HTML with Vanilla Javascript if element doesn't exists in DOM

Im trying to add an element to the DOM, but want to add it only if the element doesn’t exist. Since I will use the function in a ajax call as well, it would repeat itself, hence I need to check if the element already exists.

With jQuery this is easy:

if( jQuery(".class").length == 0){
jQuery("<div class='new_div'></div>").appendTo(".toolbar-sorter");
}

How to I do the same check with vanilla JS? Current code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const element = document.querySelector(".toolbar-sorter")
element.insertAdjacentHTML("beforeend", "<div class='new_div'></div>");

>Solution :

Something like this?

const element = document.querySelector(".toolbar-sorter")

if (document.querySelectorAll(".class").length == 0) {
  element.insertAdjacentHTML("beforeend", "<div class='new_div'></div>")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading