How to CSS: select element based on inner HTML [duplicate]
<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.
This is not possible using CSS. You can, however, do it using jQuery. There's a nice blog post on it you can read.
It's currently not possible for all browsers with css, but with javascript you can do this
Updated w/ working code. JSFiddle link below:
Initial HTML per @whamsicore:
<a href="example1.com"> innerHTML1 </a>
<a href="example2.com"> innerHTML2 </a>
<a href="example3.com"> innerHTML3 </a>
JavaScript:
var myEles = document.getElementsByTagName('a');
for(var i=0; i<myEles.length; i++){
if(myEles[i].innerHTML == ' innerHTML2 '){
console.log('gotcha');
//use javascript to style
myEles[i].setAttribute('class', "gotcha");
}
}
CSS for styling:
/* make this look a bit more visible */
a{
display: block;
}
.gotcha{
color: red;
}
https://jsfiddle.net/kjy112/81qqxj23/
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.