1

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.

1

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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';
}

Comments

1

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.

2 Comments

it appears that you've rolled back my edit. getElementsByTagName{"a"); should be getElementsByTagName("a");
No worries - I knew it was with a 27.7k user :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.