Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector to find label in pure JS

Tags:

javascript

Strictly using JS, I want to select a label element and add a class.

document.querySelector('[for=foobar]').className = "foo";

What should go in the querySelector to find <label for="foobar">?

The error I'm getting is Uncaught SyntaxError: Failed to execute query: '[for=foobar]' is not a valid selector.


Ok, I actually solved it by adding quotes around foobar, so it reads:

document.querySelector('[for="foobar"]').className = "foo";
like image 300
stevenspiel Avatar asked Dec 20 '13 03:12

stevenspiel


People also ask

How do you use the querySelector method in Javascript?

The querySelector() method returns the first element that matches a CSS selector. To return all matches (not only the first), use the querySelectorAll() instead. Both querySelector() and querySelectorAll() throw a SYNTAX_ERR exception if the selector(s) is invalid.

Can we use querySelector for ID?

With a querySelector statement, you can select an element based on a CSS selector. This means you can select elements by ID, class, or any other type of selector. Using the getElementById method, you can only select an element by its ID. Generally, you should opt for the selector that most clearly gets the job done.

What does the querySelector () method do?

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.


1 Answers

If you're looking for a <label> tag specifically, you would use:

document.querySelector('label[for="foobar"]').className = "foo";

The selector that you have will select the first element of any tag that has the given for attribute.

Here's a fiddle to demonstrate: http://jsfiddle.net/bryanjamesross/f53A4/

like image 60
rossipedia Avatar answered Sep 25 '22 07:09

rossipedia