8

I sometimes need to add elements (such as a new link and image) to an existing HTML page, but I only have access to a small portion of the page far from where I need to insert elements. I want to use DOM based JavaScript techniques, and I must avoid using document.write().

Thus far, I've been using something like this:

//  Create new image element
var newImg = document.createElement("img");
  newImg.src = "images/button.jpg";
  newImg.height = "50";
  newImg.width = "150";
  newImg.alt = "Click Me";
//  Create new link element
var newLink = document.createElement("a");
  newLink.href = "/dir/signup.html";
//  Append new image into new link
newLink.appendChild(newImg);
//  Append new link (with image) into its destination on the page
document.getElementById("newLinkDestination").appendChild(newLink);

Is there a more efficient way that I could use to accomplish the same thing? It all seems necessary, but I'd like to know if there's a better way I could be doing this.

4 Answers 4

13

There is a more efficient way, and seems to be using documentFragments if possible. Check it out: http://ejohn.org/blog/dom-documentfragments/ . Also this way should be less error prone and more maintainable than starting to mix up huge strings literals and setting them as innerHTML of some other DOM objects.

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

1 Comment

Thanks! I'll check this out for my next project.
6

Just beware, that innerHTML is both non-standard and notoriously buggy.

1 Comment

Wow, I didn't knew innerHTML was buggy! Thanks for the heads-up.
2

Nothing wrong with that. Using innerHTML would be marginally faster and probably fewer characters but not noticeable for something of this scale, and my personal preference is for the more standard, uniformly supported and safer DOM methods and properties.

One minor point: the height and width properties of <img> elements should be numbers rather than strings.

1 Comment

Thanks for the tip about height and width. That makes perfect sense.
1

If you're not adding many things, the way you've been doing it is ideal vs innerHTML. If you're doing it frequently though, you might just create a generic function/object that takes the pertinent information as parameters and does the dirty work. IE

function addImage(src,width,height,alt,appendElem,href) {...}

I do this often in my own projects using prototyping to save time.

Comments

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.