In my code I am trying to get all classes which begin with priceList_ into an array for later use. the code I used to do that is: var prefix = document.querySelector('[class^="priceList_"]').className;
There is one problem I am having with this code, which is that it only gives the first class with that prefix instead of giving an array of classes. Does anyone know the solution to this problem?
You need to be using document.querySelectorAll, document.querySelector purpose is to find the first element on the page matching the condition.
Just to add
document.querySelectorAll('[class^="priceList_"]').className
will error as the returned object is an NodeList of Nodes, not a singular Node (from which you'd be able to get the classe's).
If you wanted to obtain a structured array of each elements classe's then do the below
const classes = [...document.querySelectorAll('[class^="priceList_"]')].map(elem => elem.className);
This will assign an array of classe's (in the order of the DOM elements on the page). You could also do
const classes = [];
for (const elem of document.querySelectorAll('[class^="priceList_"]')) {
classes.push(elem.className);
}
console.log('CLASSES', classes);
querySelector() returns the first result, if you want multiple results use querySelectorAll().
Use querySelectorAll(), it gives NodeList. It is iterable.
Consider using Element.classList instead of className. You can also call classList.entries() to get an iterator.
You can also get an array from className with Element.className.split(" ")
classList on MDN Web Docs
Related
I am a novice and trying to design both relative CSS selectors and JSPath to run my automation scripts.
While on the way, I could find the return statements are different between these two. Please check the below example. Could someone tell what changes I need to make in JSPath to keep the results same as relative CSS selectors.
Result of Relative CSS selector.
Result of Relative JSPath.
JS just returns first element while the css selectors returned multiple above. What changes do I need to make in JS to keep the results same.
Document.querySelector()
The Document method querySelector() returns the first WebElement within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
Note: The matching is done using depth-first pre-order traversal of
the document's nodes starting with the first element in the document's
markup and iterating through sequential nodes by order of the number
of child nodes.
Syntax:
element = document.querySelector(selectors);
Document.querySelectorAll()
The Document method querySelectorAll() returns a static NodeList representing a list of the document's elements that match the specified group of selectors.
Note: Although NodeList is not an Array, it is possible to
iterate over it with forEach(). It can also be converted to a real
Array using Array.from(). However, some older browsers have not implemented NodeList.forEach() nor Array.from(). This can
be circumvented by using Array.prototype.forEach().
Syntax:
elementList = parentNode.querySelectorAll(selectors);
Using CssSelector
While using a xpath or a css-selectors would return a list of the document's elements that match the specified group of selectors.
Conclusion
As discussed above, when you use querySelector() only the first matching element is returned. If your usecase is to return all the matching element, you need to use querySelectorAll() as:
document.querySelector("div[slot^='Learner']>div>div>span")
You have to use
document.querySelectorAll();
How to can I treat the return value of jQuery functions that would return a bunch of DOM elements. E.g. I'm using the .nextAll() function, that returns a bunch of elements, does it? Can I store the return value in a JS array? Sooner or later I want to iterate through those elements. I know there's the jQuery .each() function that would help me out here. Nevertheless, for training and understanding issues I first want to do it step by step.
I'm pretty sure, this basic question is answered somewhere, but I searched for an answer and did not find anything useful for me. Maybe I didn't find the right words. So please be kind.
jQuery functions typically returns a bunch of DOM elements, it masquerades as an array.
If you run something like:
$('p').css('background-color', 'red');
jQuery will build an array of all p elements, and then applies the css() function to each of them.
If you want a single DOM item, use get with an index:
$( "li" ).get( 0 )
So, .nextAll() also typically returns a number of elements, so it is behaving just like jQuery typically does.
each() is a handy-dandy function that operates on arrays, so it will of course operate just fine on jQuery objects:
$('li + li').nextAll().each(function(i){
//glorious code
});
You could also do this:
var nexts = $('li + li').nextAll();
$.each(nexts, function(i){
//Glorious code!!
});
Hope that makes things clearer!
You can just assign it to a variable:
var $els = $(selector).nextAll();
This way, $els will be a jQuery wrapper (array-like object) of the elements.
If you want to have an array of the elements instead, you can use
var arr = [].slice.call($els);
As the documentation of .nextall() says, it returns jQuery
A jQuery object contains a collection of Document Object Model (DOM)
elements that have been created from an HTML string or selected from a
document. Since jQuery methods often use CSS selectors to match
elements from a document, the set of elements in a jQuery object is
often called a set of "matched elements" or "selected elements".
The jQuery object itself behaves much like an array; it has a length
property and the elements in the object can be accessed by their
numeric indices [0] to [length-1]. Note that a jQuery object is not
actually a Javascript Array object, so it does not have all the
methods of a true Array object such as join().
How can I remove all the elements with a specific tag name using Javascript. For example, I did the following:
var els = document.getElementsByTagName("center");
and it returned an array of all the center elements. How may I remove all these elements?
Coming from Remove all child elements of a DOM node in JavaScript and JavaScript DOM remove element I know that I can loop through els, find the parent of each element and then remove that specific node. But is there anyother way provided by javascript. Like we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?
With the mention that you still loop over the elements (there is no way to avoid that), you can do this:
Array.prototype.slice.call(document.getElementsByTagName('center')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
DEMO: http://jsbin.com/OtOyUVE/1/edit
Some notes on slice:
document.getElementsByTagName doesn't return an array, it returns a live list with a length
property. That is why it is needed to first convert it into an array (Array.prototype.slice does that for any object with the length property). By doing that you eliminate the problem of the list being live (gets updated when you change the DOM) and you also get the other array functions to work (like forEach) which have a more functional syntax for looping.
"it returned an array of all the center elements."
Well, it returned an array-like object (a live NodeList or an HTMLCollection depending on the browser).
"How may I remove all these elements?"
You have to loop through the list removing them one at a time as you mentioned later in your question. If you find yourself doing that a lot, encapsulate the looping inside a function so that you don't have to repeat it.
"we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?"
jQuery is a collection of JavaScript functions, so it can't do anything JavaScript can't do. jQuery's .remove() method (like most other jQuery methods) will loop internally, it just saves you having to think about it. So that comes back to what I already mentioned above, encapsulate the loop/remove code in a function so that you can use it from any part of your code.
I need to be able to store the current selectors in the current viewport and then 10 seconds check if they are still in the users current viewport.
My solution for this was to store the selectors in an array and then in 10 seconds compare the old selectors against the new and see if any match. If they do... do something.
So i believe using .each and build the array, unless somebody has a more elegant solution to this?
$('.gridContainers:in-viewport')
This will return a standard selectors.
Calling $(selector) returns an array-like jQuery object, not an actual JavaScript array, though for the purposes of what they're trying to do converting it to an actual array may be unnecessary.
This is how one would turn a selector into an native Javascript array.
$(selector).toArray()
Jquery.toArray()
With ES6 :
Array.from($(selector)); // return JS array
Try Out FIND method as Below:
$('element').find('selection');
This will give all selected elements to Array. Hope this helps
I have a line of code that uses mootools to get an array of elements with the given selectors
var menuItems = $$('#container .menu');
I need to convert this to jquery but can't find a solution. I have tried jQuery('#container .menu') but it doesn't return an array.
Is there a way to use '.find()' from jquery on the whole document ? (since I don't have a parent element to make it like parent.find()..)
Any other suggestion is also most welcome
With jQuery your statement:
jQuery('#container .menu')
will return a jQuery object that contains all matching elements where you can access the individual DOM elements with array-like syntax:
var menuItems = jQuery('#container .menu');
menuItems.length // gives a count of how many matched
menuItems[0] // the first matching element
// but you can also use jQuery methods on the object
menuItems.hide();
If you want an actual array rather than an array-like object you can use jQuery's .toArray() method:
var menutItemsArray = jQuery('#container .menu').toArray();
Why don't you try one of the jQuery tutorials available at the jQuery website?
If you absolutely need it as an array, rather than working with the jQuery object returned by the selector, take a look at the .toArray() function.