I am trying to use JavaScript to insert new elements in my HTML file.
My HTML file looks like this
<header>
</header>
<section>
</section>
<main>
<p id="time"></p>
</main>
<footer>
</footer>
<script src="first.js">
</script>
I have been inserting elements for now just in the body tag, by using
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
When JavaScript inserts the elements, it just puts them at the bottom of the HTML file,
<footer>
</footer>
<script src="first.js">
</script>
<h1>text</h1>
I want to know how to insert elements directly into my the HEADER tags WITHOUT using id's or other div's.
<header></header>
Like this
<header>
<h1>text</h1>
</header>
<section>
</section>
<main>
<p id="time"></p>
</main>
<footer>
</footer>
<script src="first.js">
</script>
Thanks!!!
I am trying to use JavaScript to insert new elements in my HTML file.
My HTML file looks like this
<header>
</header>
<section>
</section>
<main>
<p id="time"></p>
</main>
<footer>
</footer>
<script src="first.js">
</script>
I have been inserting elements for now just in the body tag, by using
var h1 = document.createElement('h1');
var content = document.createTextNode('text');
h1.appendChild(content);
document.body.appendChild(h1);
When JavaScript inserts the elements, it just puts them at the bottom of the HTML file,
<footer>
</footer>
<script src="first.js">
</script>
<h1>text</h1>
I want to know how to insert elements directly into my the HEADER tags WITHOUT using id's or other div's.
<header></header>
Like this
<header>
<h1>text</h1>
</header>
<section>
</section>
<main>
<p id="time"></p>
</main>
<footer>
</footer>
<script src="first.js">
</script>
Thanks!!!
Share Improve this question asked Apr 19, 2016 at 15:34 stefan.kenyonstefan.kenyon 3391 gold badge5 silver badges16 bronze badges1 Answer
Reset to default 5You can use document.getElementsByTagName('header')[0].appendChild(h1);
jsFiddle example
You may also try something like this:
// Get all headers
var headers = document.getElementsByTagName('header');
headers[0].appendChild(h1); // inserts into first header
headers[1].appendChild(h1); // inserts into second header
// And so on...
Also you can loop. Alternatively querySelector is another option.