-7

I am building a HTML site & that site has too many pages. So I want a code so that I can edit a particular div from my website so it will apply to all over in my website. For eg. In HTML >>

<div id="special-id"> I want to change or place anything [HTML code also] inside of this div with javascript </div>`*

& in javascript >>

<script type="text/javascript">
????
</script>

Please need help so that I can move to my HTML website again.

I want to change a content that may be simple text or a javascript code or HTML code?

1
  • Keep in mind that StackOverflow is not a place to ask questions if you didn't try anything. You'll get downvoted to oblivion for not providing anything that you tried. This answer can be answered by searching the most basic tutorial about javascript/html. Commented Jul 7, 2013 at 12:26

2 Answers 2

3
document.getElementById('special-id').innerHTML = "Whatever you want to replace with";
Sign up to request clarification or add additional context in comments.

8 Comments

It's best to include explanation with answers, not just code.
Working but can I add code given by ad networks, because they are mostally in javascript. So document.getElementById('special-id').innerHTML = "How to add ad code"; same as HTML?
Yes, you can add HTML codes too, if thats what you are asking.
Yes but ad networks give their codes with script tag so that would also work or not ?
"; }//]]> this error comes Please help
|
1

The easy way: first, get your element with e.g. getElementById, then set innerHTML to your new code.

var div = document.getElementById('special-id');
div.innerHTML = '<span>hello world</span>';

The DOM method only way: create your new HTML nodes using document.createElement or document.createTextNode and then append them to your element with appendChild.

// assuming `div` as above
var newNode = document.createElement('span');
span.appendChild(
    document.createTextNode('hello world')
);
div.appendChild(span);

2 Comments

I think .innerHTML is the best method!
It's easy, true, but it means if you'd like to do more complicated things, such as attaching event listeners, you have to get the nodes and attach the listeners after string has been parsed they've been added to the DOM tree, and not before. It also means you can't do weird things like image caching or sending virtual events to nodes not in the tree.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.