最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Insert Element into Header - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论