Quốc Cường
Quốc Cường

Reputation: 495

How to use document.getElementByTagName() with body tag

I tried using the document.getElementsByTagName() method with the body tag but it didn't work.

var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.getElementByTagName("body");
parent.appendChild(p);

Why does it not return results, where did I make a mistake?

Upvotes: 0

Views: 785

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92677

Try (however easier access to body is by document.body what was mention in James Allen answer)

let body = document.getElementsByTagName("body")[0];

body.innerHTML += "<p>This is new</p>";

Upvotes: 0

James Allen
James Allen

Reputation: 1019

document.body will return the single element as opposed to getElementsByTagName() which will return an HTMLCollection

var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.body;
parent.appendChild(p);

Upvotes: 2

GRS
GRS

Reputation: 1967

The command is getElementsByTagName, notice the plural on Elements.

var parent = document.getElementsByTagName("body");

Upvotes: 1

Related Questions