-3

Any idea how to check Dom elements is present or not in plain javascript using id

I was searching for stack overflow and some discussions but every answer is pointing towards jquery if($('#frameBox').length == 0) { .... }

I have tried something like if(document.getElementById('frameBox').length == 0) but it is not working

ojus kulkarni
  • 1,877
  • 3
  • 25
  • 41
  • 1
    `getElementById('frameBox')`. The `#` is jQuery's way of identifying an ID – j08691 Feb 23 '18 at 03:14
  • What do you want? A count of all elements? – Austin T French Feb 23 '18 at 03:17
  • Possible duplicate of [Check if a div exists with jquery](https://stackoverflow.com/questions/6899175/check-if-a-div-exists-with-jquery) – Rafael Herscovici Feb 23 '18 at 03:39
  • Possible duplicate of [How to check if element exists in the visible DOM?](https://stackoverflow.com/questions/5629684/how-to-check-if-element-exists-in-the-visible-dom) – Herohtar Feb 23 '18 at 04:38
  • Check out [my answer](https://stackoverflow.com/questions/48940533/how-to-check-dom-element-is-present-or-not-in-plain-javascript/48940566#48940566) @ojusKulkarni for a detailed explanation – Angel Politis Feb 24 '18 at 01:06

3 Answers3

3

Your code doesn't work, because getElementById returns a single HTML element, not an array-like collection of elements that has a length property, which you can get.

Also, note that, since you're trying to get an element by its id, you'll end up having one element returned at all times anyway, or null, if there's no element matching the given id.

For multiple grouped elements, try using classes and getElementsByClassName or querySelectorAll. Then, you can use length on that.

Example Code:

// Check if an element with id 'frameBox' exists.
if (document.getElementById("frameBox")) {
  //...
}

// Check if there are any elements with class 'frameBox'.
if (document.getElementsByClassName("frameBox").length) {
  //...
}
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
0

Use querySelectorAll: eg:

var elements = document.querySelectorAll("#frameBox");
console.log(elements.length);

Although, you should not use the same id on multiple elements, that's what classes are for.

koosa
  • 2,966
  • 3
  • 31
  • 46
0

id of an element is supposed to be unique. So document.getElementById would return only one element.

You can use a class instead of id. document.getElementsByClassName return all the elements which matches with the class.

Kusuma
  • 266
  • 2
  • 10