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?

2 Answers 2

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

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

3 Comments

so when i set the attributes, how would I set what I want to add? Like elementToAppend = <html here> ? Thanks!
+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.
@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);
0

appendChild is what you're looking for.

2 Comments

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

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.