Selecting direct checkbox from console

Asked

Viewed 59 times

2

Good afternoon guys, I’m having a question, I need to select several automatic checkbox to get faster the process of creating a new user.

But I don’t know what to do.

I put the following code in the console and it returns error, below codes

document.getElementTagName("input").checked = true;

My input:

<input type="checkbox" name="permission[access][]" value="common/security">

Error:

Uncaught TypeError: document.getElementTagName is not a function
at <anonymous>:1:10

What would be the most appropriate function to perform this procedure? Can I use either by tag, name or value. It doesn’t matter

Thank you in advance

  • 4

    The getElementTagName function does not exist. The correct one would be getelementsbytagname which returns an array of elements.

  • 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

1 answer

3


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;

Browser other questions tagged

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