patricksweeney
patricksweeney

Reputation: 4022

Trying to append to an element using js?

I am trying to add to all <object>'s on a page a snippet of html. I understand I can access elements by tag name and that I can change the element, but can I simple append to it instead?

In addition, I want to add it to the contents of each tag, not the end of the document. Which of these methods will work?

Upvotes: 0

Views: 1754

Answers (2)

eyelidlessness
eyelidlessness

Reputation: 63519

Assuming no library...

var elementToAppend = document.createElement(tagName); // Your tag name here

// Set attributes and properties on elementToAppend here with
// elementToAppend.attribute = value (eg elementToAppend.id = "some_id")
// You can then append child text and elements with DOM methods
// (createElement or createTextNode with appendChild)
// or with innerHTML (elementToAppend.innerHTML = "some html string")

var objects = document.getElementsByTagName('object');
for(var i = 0; i < objects.length; i++) {
    elementToAppend = elementToAppend.cloneNode(true);
    objects[i].appendChild(elementToAppend);
}

Using innerHTML or outerHTML as other answers have suggested will likely cause problems for whatever you've embedded with <object>.

Upvotes: 5

Turnor
Turnor

Reputation: 1856

appendChild is what you're looking for.

Upvotes: 0

Related Questions