简体   繁体   中英

How to change href value using javascript or jquery?

<div class="container-fluid">
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg">
<ul class="nav pull-right">
<li>
<li>
<a href="/ContactClub">Contact Club</a>
</li>
<li>
<li class="dropdown">
</ul>
</div>

I want to change the href value "/ContactClub" to "somethingelse". How is this done please?

Two ways ;)

jQuery style:

// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');

Pure-js solution (untested)

var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
 if (element[i].href === '/ContactClub') {
   if (element.setAttribute !== 'function') {
     element[i].href = 'newhref';
   } else {
     element[i].setAttribute('href', 'newhref');
   }
 }
}

You can use either prop() or attr() :

$('a[href="/ContactClub"]').attr('href', 'New Href here');

or:

$('a[href="/ContactClub"]').prop('href', 'New Href here');

Fiddle Demo

I would add an id to the a tag:

<a id="contact_link" href="/ContactClub">Contact Club</a>

And then do either,

$('#contact_link').attr('href', 'new url');

or,

document.getElementById('contact_link').href = 'new url';

Note: You can also use the jQuery prop method in the same fashion as attr above. This is somewhat a matter of preference. As href is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr . Other attributes like value will depend on what you're trying to retrieve. Do a bit of research on the differences.

尝试

$("li a").attr("href","new value");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM