Anna Riekic
Anna Riekic

Reputation: 738

Change all href inside a DIV with class

I'm trying to change all href links inside a curtain DIV that uses a class. So far I have been able change all links in a page using this snippet:

function Sl(){
 var l = document.getElementsByTagName('a');
  for(i=0;i<l.length;i++){
   var cl = l[i].href;
     l[i].href = cl.replace(cl,'http://domain,com/'+cl);}
}
 window.onload = Sl;

but its not an ideal solution.

I have tried using this line:

var l = getElementsByClassName('class').getElementsByTagName('a');

but it didn't work.


Note: No Jquery solutions, JavaScript only thanks, I don't want to have to load jquery just for a small snippet.

Upvotes: 1

Views: 1895

Answers (2)

Felix Kling
Felix Kling

Reputation: 816424

querySelectorAll is a well supported method (even IE8 supports it), so you could use a simple selector to get all the a elements:

var l = document.querySelectorAll('div.class a');

I have tried using this line:

var l = getElementsByClassName('class').getElementsByTagName('a');

but it didn't work

That's because, just like getElementsByTagName, getElementsByClassName returns a list of elements. If you know that there is only one element with that class, you can directly reference it:

var l = getElementsByClassName('class')[0].getElementsByTagName('a');

Otherwise you have to iterate over the .class elements with a for loop and inside the loop call getElementsByTagName('a') to get the a elements.

Upvotes: 2

Sai Avinash
Sai Avinash

Reputation: 4753

Can you please try the following code:

var elements = document.getElementById('parentContainer').getElementsByClassName('classname');

   for (var i = 0; i < elements.length; i++)
{
        //change href's here..
}

Hope this helps..

Upvotes: 0

Related Questions