0

What is the proper way to check if an html element exist in a webpage.

I do like this:

    if (document.getElementById('container') !== null) {doThis()}

How good is this? What are other ways?

user18984
  • 57
  • 1
  • 9
  • Well that is not checking an element.... that is checking if getElementById is defined.... I assume you meant to do `if (document.getElementById("id") !== null)` That is basically on of the ways to find the element exists or not.... Any way you do it, you need to reference the element.... – epascarello Sep 21 '18 at 18:18
  • Ye, i forgot the parenthesis..(fixed) – user18984 Sep 21 '18 at 18:21
  • The answer is, that is basically how you do it.... You can doa truthy check, but it is basically the same thing... – epascarello Sep 21 '18 at 18:22
  • it should work directly work with - `if (document.getElementById('id'))` – mmk Sep 21 '18 at 18:22
  • That is good to, but I just curious if there are other ways? – user18984 Sep 21 '18 at 18:24

1 Answers1

0

Answered

I was looking for

document.body.contains(element))
user18984
  • 57
  • 1
  • 9
  • So guessing your question is not exactly what you were asking if this is your answer.... – epascarello Sep 21 '18 at 18:33
  • I just wanted to find another way. – user18984 Sep 21 '18 at 18:34
  • But that code is still requiring you to look up the element which if you used getElementById would be still null.... so you would be doing `contains(null)` which is not any better than `if(elem)`. Now how it would work with contains if you had an element reference that was not added to the DOM yet and than would not be added. `var div = document.createElement("div"); console.log(document.body.contains(div));` – epascarello Sep 21 '18 at 18:44