I have a series of links in a ul. Some have text and some do not, eg:
<ul>
<li><a href="google.com">Google</a></li>
<li><a href="yahoo.com">Yahoo</a></li>
<li><a href="bing.com">Bing</a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
<li><a href="#"></a></li>
</ul>
I want to use JQuery to apply a class only to the a tags that have text in them.
So far I have this:
var buttontext = $('ul a').text();
if (buttontext.length > 0){
$('ul a').addClass('buttoneffect');
}
But the class is still effecting all a tags. I was just wondering if someone might be able to point me in the right directions here?
Thanks
This seemed easiest when I wrote it:
$('a').filter(
function(){
var child = this.firstChild;
if (child){
return child.nodeType == 3 && child.nodeValue.length;
}
}).addClass('buttoneffect');
JS Fiddle demo.
Or in plain JavaScript:
var aElems = document.getElementsByTagName('a');
for (var i=0,len=aElems.length; i<len; i++){
var child = aElems[i].firstChild;
if (child && child.nodeType == 3 && child.nodeValue.length >= 1) {
aElems[i].className += ' buttoneffect';
}
}
JS Fiddle demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With