Besides what my friend Ghert said, that the right thing is getElementsByTagName
, there is another point to note. As this function returns a nodelist (or an array with the elements that have the specified tag), you must also specify the tag index.
For example, if you want the first element with the tag input
is changed, use the index [0]
:
↓↓↓
document.getElementsByTagName("input")[0].checked = true;
If you don’t put an index, nothing will happen to the element.
However, it is best to use a more specific selector, because the tag input
covers other types of elements and not only checkbox
. The ideal, in my opinion, was to use:
document.querySelectorAll("input[type=checkbox]")[0].checked = true;
The document.querySelectorAll
is a more specific and flexible method, where you can select the element by tag and type at the same time. This way you can select only the checkbox inputs, and not any input.
Noting that this method also returns a nodelist, if necessary indicate the desired index, where [0]
is the first, [1]
the second and so on.
Now, if you only have 1 checkbox element, you can use document.querySelector
, that unlike the document.querySelectorAll
, will only take the first element you find, and as it does not return a nodelist, does not need index:
document.querySelector("input[type=checkbox]").checked = true;
The getElementTagName function does not exist. The correct one would be getelementsbytagname which returns an array of elements.
– Ghért B. König
That’s right, if you want to formulate an answer for me to give correctly, I’m going to create another question with a little deeper question about
– Andre Lacomski