0

I have HTML like :

<div id="divid">
  <a href="d#link1">1</a>
    <a href="d#link2">2</a>
    <a href="d#link3">3</a>
    .....................
</div>

I have script to get all links from a div like :

<script>
    var links = document.getElementById('divid').getElementsByTagName('a') ;
</script>

Then I want write link into class like :

<script>
        var links = document.getElementById('divid').getElementsByTagName('a') ;
        document.write("<div class="'+link[1]+" "+ link[i]+'">Class is added links</div>");
</script>

That mean after write I have HTML:

<div class="d#link1 d#link2 d#link3">Classes is added links</div>

How can I do this? Using for loop or not? how?

3
  • 1
    You're right, use a for loop. It's simple enough, and a google search yields many many results Commented Nov 29, 2013 at 16:15
  • JavaScript for loop. But actually your code is bad practice. Commented Nov 29, 2013 at 16:15
  • @mic perhaps you can share with him HOW it is bad practice? ;-) Commented Nov 29, 2013 at 16:23

2 Answers 2

3

You have to get the href property from each element. Put them in an array, and you can just join the strings:

var elements = document.getElementById('divid').getElementsByTagName('a');
var links = [];
for (var i = 0; i < elements.length; i++) {
  links.push(elements[i].href);
}
document.write("<div class="' + links.join(" ") + '">Class is added links</div>");
Sign up to request clarification or add additional context in comments.

Comments

1

Use join in combination with map:

var classString = links.map(function(link) { return link.attributes.href; } ).join(' ');

2 Comments

The downvote was probably because you were joining the elements, as that's what the answer said when you got the downvote. No downvote from me, but note that the map method doesn't exist in IE until version 9.
thanks domi. I highly appreciate your help. vote up for your answer.

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.