Home » Html » How to CSS: select element based on inner HTML

How to CSS: select element based on inner HTML

Posted by: admin November 30, 2017 Leave a comment

Questions:
<a href="example1.com"> innerHTML1 </a>
<a href="example2.com"> innerHTML2 </a>
<a href="example3.com"> innerHTML3 </a>

I want to style the second only (innerHTML2) using CSS selectors, based on the inner HTML. Is this possible? I’ve tried using a[value=innerHTML2] but it doesn’t seem to work.

Answers:

This is not possible using CSS. You can, however, do it using jQuery. There’s a nice blog post on it you can read.

Questions:
Answers:

It’s currently not possible for all browsers with css, but with javascript you can do this

var myEles = document.getElements('a');
for(var i=0; i<myEles.length; i++){
    if(myEles[i].innerHTML == ' innerHTML2 '){
         console.log('gotcha'); 
         //use javascript to style
    }
}

Questions:
Answers:

Using CSS you can’t detect the content of the anchor tag.

[value=] would refer to an attribute on the tag

<a href="" value="blah"> innerHTML2 </a>

Not very useful since the value attribute isn’t valid HTML on an a tag

If possible, slap a class on that a tag. As that is most likely not possible (because you would’ve already done that) you can use jQuery to add a class on that tag. Try something like this:

   <script type="text/javascript">
        $(function(){ $('a:contains(innerHTML2)').addClass('anchortwo'); });
    </script>

And then use .anchortwo as your class selector.

Questions:
Answers:

you can use the css nth-child property to access any element and do any changes. i Used it on a website i made to make a logo smaller or bigger based on the width of screen.

Questions:
Answers:
<style>
a[data-content]::before {
  content: attr(data-content);
}
a[data-content="innerHTML2"] {
  color: green;
}
</style>
<a href="example1.com" data-content="innerHTML1">&nbsp;</a>
<a href="example2.com" data-content="innerHTML2">&nbsp;</a>
<a href="example3.com" data-content="innerHTML3">&nbsp;</a>

Questions:
Answers:

This is quite simple with a nth-child selector.

<style>
a:nth-child(2) {
  color: green;
}
</style>
<a href="example1.com"> innerHTML1 </a>
<a href="example2.com"> innerHTML2 </a>
<a href="example3.com"> innerHTML3 </a>

Edit: Here’s the source I found this at. Check here for browser compatability.
Source: http://reference.sitepoint.com/css/pseudoclass-nthchild