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";
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With