-4

Is it possible to get only one DOM contains by tag name without ID and class?

As you know, in HTML5 <main>, <header> and other new tags has been added, and thanks to it, to define the style of header or footer, assigning the class or id line <div class="header"> becomes unnecessary.

E. g. I need to get the <header> contains, like

var test = document.getElementById("test");

by don't want to assign ID or class to header (nothing difference between <div id="header"> and <header id="header">. However

var test = document.getElementsByTagName("header") ;

will not work (I mean will not save the <header> contains in variable value) even if there is only one header in the page.

Anything that I can to do?

Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124
  • 2
    Like `document.getElementsByTagName("header")[0]`? Possible duplicate of [What does getElementsByClassName return?](http://stackoverflow.com/q/10693845/1529630) – Oriol Jul 08 '16 at 03:29
  • 1
    what is a DOM contains? Are you referring to a DOM node reference? – zzzzBov Jul 08 '16 at 03:29
  • zzzzBov, I mean e. g. the contains of

    test

    is

    test

    . Sorry that I didn't use the professional language.
    – Takeshi Tokugawa YD Jul 08 '16 at 03:50

2 Answers2

2
document.getElementsByTagName('header') 

will store all the header which is in the page in array.

var test = document.getElementsByTagName("header");
alert(test[0].innerHTML);
alert(test[1].innerHTML);
<header>first test</header>
<header>second test</header>

Reference link here

bubesh
  • 426
  • 1
  • 4
  • 15
1

If you don't want to assign id or class names and want to use tag name. Then it is also fine with or without html5.

var test = document.getElementsByTagName("header") ;

You are not able to get value as test is array here , notice method name is getElementsByTagName instead of getElementByTagName.

So for getting value you need to traverse through this array and if you know it has only one header element then you can simply fetch using index.

     var myValue = test[0].innerHtml;
Panther
  • 3,312
  • 9
  • 27
  • 50