1

I'm creating a new DOM element so I can later populate it with data:

var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);

I want to iterate over links in this newly created element to turn addresses like "something.something" into "http://www.something.something". I don't want jQuery, so I tried this without success:

var links = bubbleDOM.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].href = "http://www." + links[i].href.value;
}
8
  • 1
    What does your debugger say links is? Is it finding anything? Commented Feb 2, 2012 at 20:36
  • i'm not using any debugger mate Commented Feb 2, 2012 at 20:37
  • When/how are the link tags added to bubbleDom? Commented Feb 2, 2012 at 20:38
  • 3
    You should always try debugging JS before asking the community. Commented Feb 2, 2012 at 20:38
  • 1
    @josh.trow, well apparently he doesn't... =/ Commented Feb 2, 2012 at 20:45

3 Answers 3

1

Couple of things stand out.

  1. links[i].href.value isn't valid. Just use links[i].href.
  2. You should check to make sure the href actually has something in it.

Here is an example that works for me:

var links = bubbleDOM.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    if (!!links[i].href && links[i].href.length > 0) { // Check that there is an href
        links[i].href = "http://www." + links[i].href;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

links[i].href.value will always be an absolute URL, so if the attribute in HTML looks like

<a href="something.something">

then the value of links[i].href.value will be something like

"http://current.domain/something.something"

Try using getAttribute('href') instead.

Comments

0

use getters and setter to access/modify the attributes : getAttribute and setAttribue.

Here's a demo : http://jsfiddle.net/rF9qk/

2 Comments

hey thanks. it's not even getting inside the loop.. tried to put an alert inside it.. i know there are 15 links so would could be the problem?
could you post a fiddle with your code, or link us to your page?

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.