Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one attribute with another using jQuery

Tags:

jquery

dom

Using jQuery and given this

<ul>
<li>
<a external="http://stackoverflow.com" href="home.htm">Link 1</a>
</li>
<li>
<a href="about.htm">Link 2</a>
</li>
<li>
<a external="http://google.com" href="contact.html">Link 3</a>
</li>
</ul

I want to grab the links with a attribute of "external". Use the value of the external attribute to update the href.

So link 1 and 3 should end up pointing to stackoverflow.com and google.com respectively.

like image 259
jamjam Avatar asked Nov 22 '25 23:11

jamjam


2 Answers

$('a[external]').each(function(i, el){
  $(el).attr('href', $(el).attr('external'));
});
like image 136
osahyoun Avatar answered Nov 25 '25 17:11

osahyoun


Put this in $(document).ready body:

$('li a[external]').each(function() {
   var ext = $(this).attr('external');
   $(this).attr('href', ext);
});
like image 35
Michal B. Avatar answered Nov 25 '25 16:11

Michal B.