Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: adding class to element if it has text

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

like image 264
MeltingDog Avatar asked Mar 16 '26 00:03

MeltingDog


1 Answers

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.

like image 106
David Thomas Avatar answered Mar 18 '26 14:03

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!