Logan Serman
Logan Serman

Reputation: 29880

Changing a link's href attribute based on it's text with jQuery

I have seen similar threads and have tried the syntax's in their solutions, but nothing is working.

I want to change the href attribute of all links of a certain type a page, based on the text of the link. Here is what I have now:

$('.class li a').attr('href', '#' + $(this).text());

$(this).text() doesn't seem to be returning anything. It has been awhile since I've worked with jQuery so I am confused by this problem. I have also tried .val() and .html().

Upvotes: 3

Views: 921

Answers (3)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

The this reference $('.class li a').attr('href', '#' + $(this).text()); is not the link tag.. jQuery offers 2nd arg to also be a function inside which this will be referring to the link tag.. So something like below should do the trick.

DEMO

Try,

$('.class li a').attr('href', function () { 
    return '#' + $(this).text()
});

Upvotes: 1

Fabian
Fabian

Reputation: 3495

$(".class li a").each(function(){
    $(this).attr('href', '#' + $(this).text()); 
});

Upvotes: 0

Stelian Matei
Stelian Matei

Reputation: 11623

In this context, $(this) is not referencing the current a tag.

You can try this:

$('.class li a').each(function(){ 
       $(this).attr('href', '#' + $(this).text());
});

Upvotes: 4

Related Questions