jQuery - all anchors contained within <li> that have a specific class

Hello, all,

I’ve got a small bit of code that will check all anchors on a page to see if they have a title. If they do NOT have a title, or if they do have a title but it is blank, this will take the .text() of the anchor and set that as the anchor title.

What I would like to do is apply this to ONLY anchors that are within <li></li> tags that have a specific class.

<li class="rmn"><a href="http://www.helloworld.com">Hello World</a></li><!-- will have "Hello World" set as title -->
<li class="rmn"><a href="http://www.foobar.org">Foo Bar</a></li><!-- will have "Foo Bar" set as title -->
<li class="noway"><a href="http://www.noway.net">NO WAY!</a></li><!-- no title added -->

$(document).ready( // currently applies to ALL anchors - how to do only class "rmn" anchors?
    function(){
        $('a').each(function(){
             if((!$(this).prop('title')) || ($(this).prop('title') === '')){
                   var thisTitle = $(this).text();
                   $(this).prop('title',thisTitle);
                   }
        });
});

V/r,

:slight_smile:

untested

$('li a.some-class').prop('title', function (i, title) {
    return title || this.textContent;
});

Thanks, @Dormilich, I’ll give that a shot.

V/r,

:slight_smile:

Initially it didn’t work but I was able to tweak it:

$(document).ready( 
    function(){
        $('div').not('#primarymenu #secondarymenu').find('ul li a').each(function(){
             if((!$(this).prop('title')) || ($(this).prop('title') === '')){
                   var thisTitle = $(this).text();
                   $(this).prop('title',thisTitle);
                   }
        });
});

Thanks!

V/r,

:slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.