-3

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:

const element = document.querySelector(".toolbar-sorter")
element.insertAdjacentHTML("beforeend", "<div class='new_div'></div>");
Jerry
  • 1,069
  • 2
  • 13
  • 31
  • 2
    It's pointless to post jQ/JS DOM manipulations without the HTML. – zer00ne Oct 21 '22 at 08:44
  • @secan I update the question. The function will run on ajaxComplete as well, so it will duplicate if I dont have a check. The jQuery function works well, but I want it in Vanilla JS. – Jerry Oct 21 '22 at 08:45
  • There is a vanilla-javascript version on this existing question: [Is there an exists in javascript](https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – freedomn-m Oct 21 '22 at 08:56

1 Answers1

3

Something like this?

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

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

Edit: so apparently jQuerys appendTo function iterates all elements with the specific selector and appends to each of them (I did not know this, thanks @pilchard).

So a more "correct" conversion could be:

if (document.querySelectorAll(".class").length == 0) {
  const elements = document.querySelectorAll(".toolbar-sorter")

  elements.forEach(element => {
    element.insertAdjacentHTML("beforeend", "<div class='new_div'></div>")
  })
}
Bqardi
  • 682
  • 3
  • 10
  • [`appendTo`](https://api.jquery.com/appendTo/) inserts into every matched element, so as @Teemu commented, you would need to `querySelectorAll(".toolbar-sorter")` and iterate the nodeList inserting into each matched element. – pilchard Oct 21 '22 at 08:50
  • You can shorten `document.querySelectorAll(".class").length == 0` to `!document.querySelector(".class")`. Also you could probably skip the lookup of `elements` if it already exists. – Lain Oct 21 '22 at 09:13
  • I know @Lain, just wanted to write code that more resembled the jQuery code he posted. – Bqardi Oct 21 '22 at 09:16
  • Alright, makes sense. – Lain Oct 21 '22 at 09:17
  • But you are right about the elements lookup. Should have propably been moved inside the if statement, I'll edit. – Bqardi Oct 21 '22 at 09:20