Hello!

Tell me, please, how to get a NodeList using getElementById? By default, HTML is returned with children. eg

HTML:

<div id="text"> <p>text</p> </div> 

Js:

 el = document.getElementById('text'); console.log(el) 

However, if you use jQuery console.log($(el)) , then you get a NodeList. Tell me, please, how to achieve the same result on classic JavaScript.

Thank!

  • one
    getElementById - returns a link to a single Element . developer.mozilla.org/ru/docs/Web/API/Document/getElementById - Sublihim
  • @Sublihim, How do I get a NodeList? There is a function el.childNodes, but it will return all child nodes - Pavel
  • See the answers below - Sublihim
  • ... but jQuery actually returns a jQuery object, that is, itself in the prototype, not a NodeList ... console.log(el instanceof jQuery, el instanceof NodeList); //true, false console.log(el instanceof jQuery, el instanceof NodeList); //true, false - Alex Krass
  • On jQuery, a wrapper is written over getElementByI, d, which most likely creates a Nodelist when it calls getElementByI вызов d. 1. You can write a similar one yourself - read classes in JS. 2. You can see how this is implemented in jQuery and even walk through the jQuery function debugger. - nick_n_a

2 answers 2

Saying that document.getElementById returns HTML - you are mistaken. This method returns an instance of the Element class.

Seeing this is quite simple. Here is the code:

 var el = document.getElementById('text'); console.log(el instanceof Element); 

will print true ( proof ) to the console.

As for the NodeList , document.getElementById in no case return an instance of this class, since, according to the standard, the id attribute must be unique within the document.

The behavior of jQuery here can be explained by considerations of uniformity: by wrapping an element ( Element ) you get a collection of nodes containing exactly one element.


If you still need a NodeList instance and you don’t want to use jQuery, you can use the document.querySelectorAll method:

 var el = document.querySelectorAll('#text'); console.log(el instanceof NodeList); 

JSFiddle working example .

    Try the document.querySelectorAll method. Example: List = document.querySelectorAll("selector");

    • Thanks for the answer. But you need to get a NodeList through getElementById - Pavel
    • 2
      @Pavel, all you can get with getElementById is an Element instance. This is how the DOM API works. Humble yourself. - Dmitriy Simushev