0

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?

patricksweeney
  • 3,939
  • 7
  • 41
  • 54

2 Answers2

5

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
  • 62,413
  • 11
  • 90
  • 94
  • so when i set the attributes, how would I set what I want to add? Like elementToAppend = ? Thanks! – patricksweeney Jul 22 '09 at 21:40
  • +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 Jul 22 '09 at 21:40
  • @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 Jul 22 '09 at 21:42
0

appendChild is what you're looking for.

Turnor
  • 1,836
  • 12
  • 14