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!
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!
In order to write an analogue, you must first determine what exactly happens in this piece of code:
$('#list a') - selected in <a> inside the element with id="list".each( function (key, val) {...}) - cycle through selected itemsnames.push($(val).text()); the text from the checked element is entered into the arrayEach of these actions can be found to match:
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; }) querySelectorAll - classic JavaScript? If we are in the classics, then getElementById , etc. - AstronavigatorgetElementById 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.
Source: https://ru.stackoverflow.com/questions/559639/
All Articles