简体   繁体   中英

converting code from jquery to pure javascript

I want to loop though some links and add a number to the href, so it would be something like x.php&ref=333 .

<div id="maindiv">
<span><a href="x.php&ref="></a></span>
<span><a href="x.php&ref="></a></span>
<span><a href="x.php&ref="></a></span>
</div>

How do I write this in pure javascript? Here is the jQuery code:

$('#maindiv a').each(function(){
var hr = $(this).attr('href');
$(this).attr('href' , hr+333 );
})

For some reason I can't use that and need to write the code in pure javascript . Specifically, I don't know how to get each a element.

Pure JS versions:

Option One

// Get div element. jQuery equivalent: $('#maindiv')
var mainDiv = document.getElementById("maindiv");

// Get all anchors in element. jQuery equivalent: $('#maindiv a') (or many others)
var myAnchors = mainDiv.getElementsByTagName("a");

// Loop through each anchor element and update href
for (var i = 0; i < myAnchors.length; i++) {
    myAnchors[i].href = myAnchors[i].href + "YourString";
}​

Option Two (tiny bit less readable)

// Get div element and corresponding anchors. jQuery equivalent: $('#maindiv a')
var myAnchors = document.getElementById("maindiv").getElementsByTagName("a");

// Loop through each anchor element and update href
for (var i = 0; i < myAnchors.length; i++) {
    myAnchors[i].href = myAnchors[i].href + "YourString";
}​

Additional Information

Check out document.getElementById and element.getElementsByTagName ON MDN.

Try this.

var anchors = document.getElementById("maindiv").getElementsByTagName("a");
for(var i = 0; i < anchors.length;i++){
    anchors[i].href = anchors[i].href + "333";
}

document.getElementById returns the element with matching id within the document.

document.getElementsByTagName returns the element with matching tag within the document. But if you call getElementsByTagName on an already selected element like above it will look within that element.

var els = document.querySelectorAll('#maindiv a');
for (var i = 0; i < els.length; i++ ) {
    var hr = els[i].href;
    els[i].href = hr + 333;
}

This should be the cleanest way to do it.

var links = document.getElementById('maindiv').getElementsByTagName('a');
for (i in links) {
  links[i].href = links[i].href + '333';
}

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