max
max

Reputation: 3716

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.

Upvotes: 1

Views: 1818

Answers (4)

ShankarSangoli
ShankarSangoli

Reputation: 69905

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.

Upvotes: 1

James Hill
James Hill

Reputation: 61793

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.

Upvotes: 3

Steve Davis
Steve Davis

Reputation: 1009

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

Upvotes: 1

Paul Grime
Paul Grime

Reputation: 15104

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

Upvotes: 1

Related Questions