How to select all non-empty anchor links with a CSS selector?

Viewed 4515

Hey there I am searching for a CSS selector to select all non-empty anchor links, where the anchor itself is not empty.

I already have a selector in order to select all links having an anchor attribute - see this example:

a[href*=\#] {
  background-color:#f00;
}
<div id="sample">
<p>
Hey bro, yesterday I was walking about 50 
<a href="http://www.example.com">example</a> 
kilometers down this shiny road. 
After watching <a href="#friends">my friends</a> smoking a 
<a href="#">shiny cigarette</a> the air became dark 
<a href="http://example.com/#">and</a>
 my fancyness 
<a href="http://www.example.com/#inc">increased</a>.
</p>
</div>

However what I want is to select all anchors with href="#something", while excluding all anchors where href="whatever#".

Such that "shiny cigarette" and "and" would not be selected.

May you help me out on this?

2 Answers

a[href*=\#]:not([href$=\#]) {
  background-color: #f00;
}
<div id="sample">
  <p>
    Hey bro, yesterday I was walking about 50
    <a href="http://www.example.com">example</a> kilometers down this shiny road. After watching <a href="#friends">my friends</a> smoking a
    <a href="#">shiny cigarette</a> the air became dark
    <a href="http://example.com/#">and</a> my fancyness
    <a href="http://www.example.com/#inc">increased</a>.
  </p>
</div>

In the example above, all attribute values containing (*) # are selected, but those values ending with ($) # are excluded.

a[href*="value"] - the attribute value *contains* the specified value
a[href$="value"] - the attribute value *ends with* the specified value
a[href^="value"] - the attribute value *starts with* the specified value
a[href="value"]  - the attribute value *matches exactly* the specified value

More here: https://www.w3.org/TR/css3-selectors/#selectors

a[href^=\#] {
  background-color:#f00;
}

^= operator means starts with

Is this what you wanted?

To eliminate # followed by nothing

a[href^=\#]:not([href=\#]) {
      background-color:#f00;
    }
Related