Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 738
Blackbam Avatar asked Nov 03 '17 15:11

Blackbam


People also ask

How do I select an anchor tag in CSS?

The :link selector is used to select unvisited links. Note: The :link selector does not style links you have already visited. Tip: Use the :visited selector to style links to visited pages, the :hover selector to style links when you mouse over them, and the :active selector to style links when you click on them.

Can you select multiple HTML elements with a single CSS selector?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

How do I select all HTML elements in CSS?

The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").


1 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

like image 143
Michael Benjamin Avatar answered Nov 10 '22 00:11

Michael Benjamin