3

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

1
  • Can you just alert the value of buttontext and check? Commented Jul 12, 2012 at 3:29

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$('ul a').each(function()
               {                                        
                  if($(this).text()!='')    
                  {
                     $(this).addClass('buttoneffect');   
                  }
               });

Check http://jsfiddle.net/uawBL/11/

Comments

0
$("ul a").each(function (i, e) {
    var $e = $(e);
    if ($e.text().length > 0) {
        $e.addClass("buttoneffect");
    }
});

2 Comments

Thanks. Just curious does the i in that function auto increment or something? Whats the purpose of it?
@MeltingDog: you might want to get familiar with the jQuery docs: yes, the i argument is the index of the element in the list found by the selector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.