How to select label for="XYZ" in CSS?

CssCss Selectors

Css Problem Overview


label {
  display: block;
  width: 156px;
  cursor: pointer;
  padding-right: 6px;
  padding-bottom: 1px;
}

<label for="email">{t _your_email}:</label>

I wish to select the label based on the 'for' attribute to make layout changes.

Css Solutions


Solution 1 - Css

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

Solution 2 - Css

If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:

itemSelected(id: number){
console.log('label contains', document.querySelector("label[for='" + id + "']"));
}

Solution 3 - Css

If the label immediately follows a specified input element:

input#example + label { ... }
input:checked + label { ... }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKyleView Question on Stackoverflow
Solution 1 - CssT.J. CrowderView Answer on Stackoverflow
Solution 2 - CssJulio Cesar Brito GomesView Answer on Stackoverflow
Solution 3 - CsscloseView Answer on Stackoverflow