This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 6 months ago.
I have an array of strings that are valid jQuery selectors (i.e. IDs of elements on the page):
["#p1", "#p2", "#p3", "#p4", "#p5"]
I want to select elements with those IDs into a jQuery array. This is probably elementary, but I can't find anything online. I could have a for-loop which creates a string "#p1,#p2,#p3,#p4,#p5" which could then be passed to jQuery as a single selector, but isn't there another way? Isn't there a way to pass an array of strings as a selector?
EDIT: Actually, there is an answer out there already.
Well, there's 'join':
["#p1", "#p2", "#p3", "#p4", "#p5"].join(", ")
EDIT - Extra info:
It is possible to select an array of elements, problem is here you don't have the elements yet, just the selector strings. Any way you slice it you're gonna have to execute a search like .getElementById or use an actual jQuery select.
Try the Array.join method:
var a = ["#p1", "#p2", "#p3", "#p4", "#p5"];
var s = a.join(", ");
//s should now be "#p1, #p2, #p3, ..."
$(s).whateverYouWant();
What about $(foo.join(", "))?
Use the array.join method to join them together
$(theArray.join(','));
Going to officially answer your question: with a one-liner:
//If this is only one use variable you can use
$(['#p1','#p2','#p3','#p4','#p5'].join(',')).methodToUse();
//if you DO need it as a variable you can
var joined = ['#p1','#p2','#p3','#p4','#p5'].join(',');
$(joined).methodsToUse();
If you want them to do something individually there is also .each();
In the example below, each p ids clicks makes any one of them red:
var peas = ['#p1','#p2','#p3','#p4','#p5'];
$.each(peas, i => {
$(peas[i]).click(() => {
$(peas[i]).css({'color':'red'});
});
});
When you throw 'i' into a function parameter, it finds the values inside the arrays appropriately. When you do '.each()' the format looks like this:
$.each(array, function(i){
// any code you wish as long as you have an array selector
//$(array[i]).whatever function
});
An even bigger example. Say you want to make the P you click on red, but want the other ps return to default color. Just make a function that removes the selected ID from the array and voila!
var peas = ['#p1','#p2','#p3','#p4','#p5'],
poppy=(v,i)=>peas.toString().replace(`,${v[i]}`,'').replace(`${v[i]},`,'');
(// get each pea index
$.each(peas,i=>///funciton(i){ code inside}
(//set up each individual index's functions
$('.peastock').append(`<p id="p${[i+1]}">I am ${peas[i]}</p>`),
$(peas[i]).click(()=>(
$(peas[i]).css({"color":"red","background-color":"rgba(128,0,0,0.1)"}),
$(poppy(peas,i)).css({'color':'black','background-color':'rgba(255,255,255,0.2)'}))))),
$('.peastock').append(`
<div id="ree">ES6 isnt suitable for all of jQuery's usage!</div>
<div>Since some functions inside of jQuery's methods dont require 'this' or 'return'</div>
<div>You can learn this by going here</div>
`),
$("*").css({"margin":"0 auto","padding":"1%"}),
$("* .peastock, .peastock, .peastock *").css({"background-color":"rgba(128,0,0,0.1)"})
);
I know someone is bound to want to know about each value array as jquery selectors. Hope everything goes well!
Source:
jQuery .each()
The fiddle in action (with updates!)
I think you're looking for join.
var arr = ["#p1", "#p2", "#p3", "#p4", "#p5"];
$(arr.join(","))
Shorter:
$( ["#p1", "#p2", "#p3", "#p4", "#p5"].toString() );
Related
Is there a way to get an element by its content(a word it contains?)
For example, get all the elements with the letter "F," and put it in a array of elements
I highly recommand you to use jQuery for these kind of DOM elements searching.
Then you can use this:
var foos = $("div:contains('foo')" )
will make an array with all divs containing the word 'foo'.
One fairly easy way is to select the elements you're interested in and then use 'filter' to look at the innerText. You can make this case insensitive with toLowerCase
var result = $('div').filter( (i,e) => e.innerText.toLowerCase().indexOf("f")>-1);
console.log("Items with 'F':",result.length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Forest</div>
<div>Fortnight</div>
<div>Trees</div>
<div>Africa</div>
The simpler way is using :contains('F') as a selector - but that is always case sensitive (which may be fine for your case).
You can use :contains as a selector. For example, to filter all divs of a special class that also contains your text, you can use $("div.myclass:contains('searched text')")
I think you can "bruteforce" it by iterating all DOM items. e.g.:
let arrayDom = Array.from(document.getElementsByTagName("*"));
arrayDom.forEach(element => {
if (element.innerHTML.contains('F')){
// Do something
}
})
In Javascript, arrays should have methods pop and shift.
However, JQuery objects seem to be missing these methods:
$('div').shift(); // Error, shift is undefined
$('div').pop(); // Error, pop is undefined
$('div').splice(); // Splice is OK actually
I wonder why these functions are missing - after all, the jquery object is just an array.
What's the easiest way of performing pop and shift functions on jquery objects?
They're missing because a jQuery object isn't an Array.
(function( $ ) {
$.fn.pop = function() {
var top = this.get(-1);
this.splice(this.length-1,1);
return top;
};
$.fn.shift = function() {
var bottom = this.get(0);
this.splice(0,1);
return bottom;
};
})( jQuery );
EDIT: .slice() doesn't modify the original object. Fixed to use .splice() instead.
Your safest bet would be to just use:
[].pop.call($('div'))
[].shift.call($('div'))
If you want to use the exact syntax in your example you can augment jQuery.fn:
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
The latter works well for the mutator methods. It'll work for the accessor and iteration methods too, but be advised that many of those returns a pure array that you'd have to rewrap. Be aware that jQuery has is own version of some of these (e.g. .map, .slice, .filter, etc.) that you probably don't want to overwrite.
This seemed to work for me:
var divArray = $('div').toArray();
var elem = $( divArray.shift() );
.toArray() return the DOM elements as a JavaScript Array, which can be used as intended. Then all you need to do is convert it back into a jQuery object.
I realize this answer has already been selected, but here's another alternative that isn't too hard to remember, in case you don't want to worry about having to install plugins all the time.
$('div > :first').detach(); // shift
$('div > :last').detach(); // pop
By the way, I realize there are performance issues with using :last selector as part of your primary selector so you may want to consider doing something like this for pop:
$('div').children(':last').detach();
var $firstDiv = $( $('div').splice(0, 1) );
Another way using jQuery 1.9.1+:
$('div').first().remove();
$('div').last().remove();
If you execute in the console on this page
var cloned = $(".question").clone(true);
$(".question").addClass("first");
var clonedStr = cloned[0].outerHTML || new XMLSerializer().serializeToString(cloned[0]);
$(".question").after(clonedStr);
you will clone the question (there will be two questions on the page, but the first one will be with the .first class). That's what is needed.
Is there any simpler way to do this with jQuery? I'm confused of the third string in the code above and believe it could be simpler. Any ideas?
Thank you.
If you don't use the HTML as string, then don't get it. Just use the jQuery object:
var cloned = $(".question").clone(true);
$(".question").addClass("first").after(cloned);
Also, you can do it one line:
$(".question").after($(".question").clone(true)).first().addClass("first");
You could use insertAfter to insert the cloned element after changing the class. You don't need to convert the element in the jQuery object to a string, you can use that object within the function itself:
var $question = $('.question');
var $cloned = $question.clone(true).insertAfter($question);
$question.addClass('first');
This question already has answers here:
How to select last child element in jQuery?
(6 answers)
Closed 9 years ago.
I am taking a fairly simple piece of code and wrapping into a function, the code builds a slide out menu from the items inside a div. I'm now trying to get the last child from a div:
experimentOne('#experimentOne');
function experimentOne(masterContainer) {
var experimentOneMenuButton = $('masterContainer :last-child');
... etc
However, this returns [] in the log. When I check the width, instead of the 100px it should be, it's 1420 which I'm guessing is the window width.
If I just get the last child of the ID by coding it in everything is fine, but I want the function to be as reusable as possible.
Thanks.
Try this if your masterContainer is an element:
var experimentOneMenuButton = $(':last-child', masterContainer);
Or this if it is a string for the element id
var experimentOneMenuButton = $('#'+masterContainer+' :last-child');
masterContainer is a variable containing the value of the parent container, so when you build the selector you need use it with string concatenation.
var experimentOneMenuButton = $(masterContainer + ' :last-child');
or you can use a context based lookup
var experimentOneMenuButton = $(':last-child', masterContainer);
I would recommend the second solution which make use of context bases lookup since it is neater.
Demo: Fiddle
element with id is selected with "#"
you need to target immediat children with ">", [space] target all descendants of element
$('#masterContainer>:last-child');
Well masterContainer inside the string will do nothing. I think it should be:
$(masterContainer).find(':last-child');
Also note that experimentOne('#experimentOne'); will send a string not a jQuery object. That would require experimentOne($('#experimentOne'));, which would leave:
experimentOne($('#experimentOne'));
function experimentOne(masterContainer) {
var experimentOneMenuButton = masterContainer.find(':last-child');
// Note the lack of jQuery wrapper around masterContainer in this version
Depends on whether you want to force a jQuery object in the parameter or in the function itself!
Your concatenation is wrong. Try that way:
$(masterContainer + ' :last-child')
Right now I have a dynamic string that assigns it's values to a particular div class.
Output looks like this
<div class="12923"></div>
I want to find that 'randNumber' div, then check if it has another class 'x'
Currently what I have now doesn't work:
var randNumber = 12923
var lookingForYou = $$('.'+randNumber);
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$ returns an Elements instance, Elements is an array-like Class
anyway since you are basically filtering, you can tell Slick that you need an element with both class:
var randNumber = 12923;
if($$('.' + randNumber +'.XCLASS').length>0){
alert('XCLASS FOUND');
}else{
//dostuff
}
or you could just use one of the Elements methods, I think .some will be your best choice here:
var randNumber = 12923
var lookingForYou = $$('.' + randNumber);
alert(lookingForYou.some(function(el){
return el.hasClass('XCLASS');
}))
EDIT:
adding some links:
A better way to use Elements on MooTools blog
in my second example I used the some method, which, by looking at the source is not overloaded, but is just the one in Array.prototype.some:
Element.js source reference
Array.some on MDN
$$ returns an array of all matching elems. Not sure if you can do a hasclass on an array. Might have to do a .each() then do it. Try $('body').getElement('.'+randNumber).hasClass('XCLASS') this way you grab 1 elem if you don't want to mess with the array.
Here:
if (lookingForYou.hasClass('XCLASS')){alert('XCLASS FOUND!');}
$$() returns an array, and hasClass() performs the check on each element of the array, returning an array of booleans. Unfortunately, when you check if (...), then the return array, even if all of the values are false, is evaluated as true because it's non-empty.