RulerNature
RulerNature

Reputation: 753

javascript selectors document.object

I am trying to select few elements into my html page and I'm wondering why I should use all the time that "document" when I'm targeting html elements for example:

//variable body

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

in next variable why I cannot use something like: get all p tags from body

var selector = content.querySelectorAll("p");

instead of using

var selector = document.querySelectorAll("p");

Upvotes: 0

Views: 61

Answers (4)

r.pedrosa
r.pedrosa

Reputation: 749

You cannot mainly because document.getElementsByTagName return a HTMLCollection.

By definition, a "HTMLCollection interface represents a generic collection (array-like object) of elements (in document order) and offers methods and properties for selecting from the list."

So, in your example, you need to use var content = document.getElementsByTagName("body")[0]; or document.body (better)

Upvotes: 1

horizon0514
horizon0514

Reputation: 21

Because getElementsByTagName() returns array. So you should use var content = document.getElementsByTagName("body")[0];

Upvotes: 1

Samurai
Samurai

Reputation: 3754

Because getElementsByTagName returns a list of elements not one, you can use;

var selector = content[0].querySelectorAll("p");

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074208

in next variable why I cannot use something like: get all p tags from body

Because getElementsByTagName returns a NodeList, not an element. It works if you grab the one element that matched:

var content = document.getElementsByTagName("body")[0];
// ------------------------------------------------^^^
var paragraphs = content.querySelectorAll("p");

But just use document.body instead:

var paragraphs = document.body.querySelectorAll("p");

(Of course, as p elements cannot be outside of body, both of those are the same as document.querySelectorAll in this specific case.)

If you want all p elements that are direct children of body, then:

var paragraphs = document.querySelectorAll("body > p");

Upvotes: 6

Related Questions