0

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");
2
  • 1
    why don't you use jquery? Commented May 13, 2015 at 8:23
  • You should really checkout the wonderful jquery library. Commented May 13, 2015 at 8:23

4 Answers 4

6

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");
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.