Hello!

There is such code on jQuery:

names = []; $('#list a').each( function (key, val) { names.push($(val).text()); }); 

What will be the analogue of the classic JavaScript?
Thank!

  • You can ask, why? jQuery got too heavy for your project? - Astronavigator

2 answers 2

In order to write an analogue, you must first determine what exactly happens in this piece of code:

  1. $('#list a') - selected in <a> inside the element with id="list"
  2. .each( function (key, val) {...}) - cycle through selected items
  3. names.push($(val).text()); the text from the checked element is entered into the array

Each of these actions can be found to match:

  1. document.querySelectorAll - for selection
  2. any cycle: for , forEach , etc.
  3. textContent , innerText , innerHTML - to get the content of the element.

Example:

 var names = []; [].forEach.call(document.querySelectorAll('#list a'), function (val, index) { names.push(val.textContent); }); 

Also, as you can see, there is a translation from one collection to another, the map method is perfect for such an operation.

 var names = [].map.call(document.querySelectorAll('#list a'), function(el){ return el.textContent; }) 
  • But is it possible to consider the code with querySelectorAll - classic JavaScript? If we are in the classics, then getElementById , etc. - Astronavigator
  • @Astronavigator, of course you can - this is a standard mechanism, it does not need additional libraries - Grundy
  • “standard” does not mean “classic” :). As I understand it, this feature is quite new. Although, maybe now any JavaScript is called classic .... - Astronavigator
  • @Astronavigator, classic is without using libraries - Grundy
  • one
    @Astronavigator, getElementById is not a classic, it's retro :) - user207618

 // JQuery names = []; $('#list a').each( function (key, val) { names.push($(val).text()); }); // pure JS names2 = []; document.querySelectorAll('#list a').forEach(function (key, val) { names2.push(key.textContent); }); console.log('names:' + names); console.log('names2:' + names2); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="list"> <li><a href="1">test1</a></li> <li><a href="2">test2</a></li> <li><a href="3">test3</a></li> </ul> 

Where

querySelectorAll - returns a list of elements within the document (the search is performed within the specified element) that correspond to the specified group of selectors. Returns an object of type NodeList.

forEach - performs the specified function once for each element in the array.

  • I'm forward :-P and also with an explanation :-) - Grundy
  • @Grundy clever daughter%) - Alexey Shimansky