views:

182

answers:

2

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?

A: 

appendChild is what you're looking for.

Turnor
I know about appendChild, but wont that add to the end of the document? I want to append it to every occurance of <object>.
patricksweeney
nope, it appends to whatever element you call the function on.
Turnor
+5  A: 

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>.

eyelidlessness
so when i set the attributes, how would I set what I want to add?Like elementToAppend = <html here> ? Thanks!
patricksweeney
+1 for an example showing how to use `appendChild()`. Also good you demonstrated `cloneNode()`. My early attempts to do this assumed you could append the same child node multiple times, with not-so-successful results.
Grant Wagner
@patricksweeney: If what you want to append is complex, you have to built it up using `appendChild` as well: `var elementToAppend = document.createElement('span'); var bold = document.createElement('b'); var text = document.createTextNode('stuff'); bold.appendChild(text); elementToAppend.appendChild(bold);`
Grant Wagner