How to check if an id exists?

Asked

Viewed 1,974 times

2

This script is not working, I just want the Thumb variable to be created if the id Thumb exists, if the script does not exist. It seems that when Thumb doesn’t exist it gives error and the script doesn’t even work. NOTE: I’m only using Notepad++, I don’t see any error messages.

if(document.getElementeByid("thumb") !== null)
{
    var thumb = document.getElementeByid("thumb");
}
comandos;
  • Just warning something for future use, when you want to know if something exists or not, compare with undefined, not with null.

2 answers

9


There is no function getElementeByid in Javascript.

  • it’s not "Elemente," it’s "Element"

  • and "Id" is capitalized.

Correct function: getElementById.

And you don’t have to call the function twice, you can reuse it like this:

var thumb = document.getElementById("thumb");

if(thumb)
{
    // faz algo se o elemento existir
}

Or else:

var thumb = document.getElementById("thumb")||(valor alternativo ou função se não existir);
  • I misspelled here but actually I’m using Document.querySelector("#Thumb").

  • querySelector for ID does not make any sense. ID is to have only one for DOM, so the appropriate function is getElementById anyway.

  • But I always use querySelector and it works.

  • 1

    "It works" is not the same as being suitable. If it’s for class, or another combination, then yes. However, getElementById is more effective whenever it can.

  • 1

    Anyway, using the get Elementbyid properly worked. Thanks.

1

Test like this:

if($('#thumb')){
   //Se existir o id verdadeiro entra aqui
}else{
   //Se não existir entra aqui.
}
  • Only works if the person is using Jquery.

  • exact obg for warning me forgot this detail, to use without jQuery switch to Document.getElementById('Thumb');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.