A
A
artegion2018-02-05 20:31:18
JavaScript
artegion, 2018-02-05 20:31:18

JS, How to check if an element with a certain ID exists on the page?

Question for the experts! I'm not strong in JS, so please help!

...
document.getElementById('поле').setAttribute('value', значение);
...

There is a js script that displays a certain value in the input id field, by default the script works on the entire site, but the form itself is not on all pages of the site, and on pages where this field is not present, an error occurs: Cannot read property 'setAttribute' of null , where there is a field, this error was not noticed.
So the question is, how to change the script so that the "existence" of the inpet id field on the site page is checked? If there is, then we display it, if not, then we do not display it!? It turns out that the page cannot find the field and displays an error!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Tsvetkov, 2018-02-05
@artegion

document.getElementById('поле') && document.getElementById('поле').setAttribute('value', значение);;

A
Ainur Valiev, 2018-02-06
@vaajnur

document.getElementById('поле').length

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question