How to check if an id exists?

0

This script is not working, I just want the thumb variable to be created if the thumb id exists, if the script does not exist. It seems that when the thumb does not exist it gives an error and the script does not work. Note: I'm only using Notepad ++, I do not see any error messages.

if(document.getElementeByid("thumb") !== null)
{
    var thumb = document.getElementeByid("thumb");
}
comandos;
    
asked by anonymous 20.09.2018 / 10:09

1 answer

8

There is no getElementeByid function in JavaScript.

  • is not "Elemente", it is "Element"

  • and the "Id" is capitalized.

Correct function: getElementById .

And you do not 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:

var thumb = document.getElementById("thumb")||(valor alternativo ou função se não existir);
    
20.09.2018 / 10:21