Jquery change attribute

I have 4 links and I need to change the href attribute in the rel attribute. I know that I can’t do this, so I'm trying to get the data from the href attribute by setting a new attribute (rel), inserting data into it, and then deleting the href attibute.

I basically do this:

$('div#menu ul li a').each(function(){ var lin = $(this).attr('href'); $('div#menu ul li a').attr('rel',lin); $(this).removeAttr('href'); }) }) 

it works, but it sets the same rel data in all the links that I have.

any help?

+4
source share
6 answers
 $('div#menu ul li a').each(function(){ var lin = $(this).attr('href'); $(this).attr('rel',lin); $(this).removeAttr('href'); }); 
+3
source

Try

 $('div#menu ul li a').each(function(){ var lin = $(this).attr('href'); $(this).attr('rel',lin); $(this).removeAttr('href'); }) }) 

Didn't actually run the code ... but it looks like it should do the trick.

+2
source

Edit:

 $('div#menu ul li a').attr('rel',lin); 

To:

 $(this).attr('rel',lin); 
+2
source

You are probably doing β€œthis” wrong. (means there is a better way to do what you are trying).

but just answer the question:

 $('#menu ul li a').each(function(){ var lin = $(this).attr('href'); $(this).attr('rel',lin).removeAttr('href'); }); 
0
source

Here is a solid jquery solution:

 $(function() { $("a.selector").on("click", function() { var trigger = $(this.hash); trigger.removeAttr("id"); window.location.hash = this.hash; trigger.attr("id", this.hash.replace("#","")); return false; }); }); 
0
source

This is problem

 $('div#menu ul li a').attr('rel',lin); 

This line applies changes to any element that matches your selector, which in your case corresponds to four links - use this code instead

 $('div#menu ul li a').each(function(){ var lin = $(this).attr('href'); $(this).attr('rel',lin); $(this).removeAttr('href'); }) }) 
0
source

Source: https://habr.com/ru/post/1307161/


All Articles