Combining selectors as variables in jQuery - javascript

I'm thinking of what is the best way to combine selector, which i use as variables in my jQuery code. I want to use selectors as variable always, but the thing is that sometimes i want to use them in one statement, so i'm thinking what's the most elegant way to do it.
Should i use add ( (x+y).function... )? Or maybe add strings? Or maybe keep jQuery variables as only id with name so i can combine within single jQuery statement ($ that is)
x = $('#selectorOne');
y = $('#selectorTwo');

You can store them in an array:
var selectors = [
'#selector1',
'#selector2',
....
];
and when you want to use them all together, do a comma separated join()
var alljoined = selectors.join(','); //join ALL selectors
$(alljoined).doSomethingToAll(); //and do something to all
you can also choose selectively:
var fewjoined = [ //select a few selectors...
selectors[1],
selectors[3],
...
].join(','); //..to join
$(fewjoined).doSomethingToAll(); //and do something

If they're declared as variables you can use add():
x.add(y).something();

Multiple Selector (“selector1, selector2, selectorN”)-You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
Example :
$("div,span,p.myClass").css("border","3px solid red");
or
.add() - Add elements to the set of matched elements.
Example :
$("p").add("div").addClass("widget");

Since x and y are just arrays, one can use jQuery.merge to combine them. HTH

Related

Difference between using eq(0) and not using it

When I want to run a jQuery function on a single element that has the class .pizza, I do this:
$('.pizza').hide();
What is the difference between that and using first() or eq(0)?
$('.pizza').eq(0).hide();
My question comes because I want to cache the element into a variable to use it many times, and I don't know if it is a better practice to do:
var element_pizza=$('.pizza').eq(0);
Or just simply:
var element_pizza=$('.pizza');
Note: When I mean on a single element, I mean that there is only one element with the class pizza in the DOM.
Thanks for your time.
There is no difference when the set contains only one match.
Using .eq() would only be to select one specific match from a set. If the set has one element, then they will be equivalent.
In fact, it is a waste to use .eq(0) if the set contains one element because that will cause a new jQuery object to be created.

Javascript selector with Regular Expression

I would like to add an event listener to 2 buttons. Their ids are:
authCreateAcctConfirmNoBtn
authCreateAcctConfirmYesBtn
How would I do the following, I imagine I am close:
authCreateAcctConfirm(No|Yes)Btn.addEventListener('blur', function() {...
I don't know how to tell the browser that the object to attach to is a regular expression?
You need to select the elements first. This is done via document.querySelector.
I would avoid crazy Regex magic and choose the straightforward way. The easiest solution would look like this:
document.querySelector("#authCreateAcctConfirmYesBtn").addEventListener("blur",func);
document.querySelector("#authCreateAcctConfirmNoBtn").addEventListener("blur",func);
function func(){
/* stuff here */
}
To select both at once, you could use querySelectorAll and use this selector:
var elements = document.querySelectorAll("#authCreateAcctConfirmYesBtn,
#authCreateAcctConfirmNoBtn");
You now have to iterate over the returned NodeList resultset with a straightforward for loop or a borrowed Array method:
Array.prototype.forEach.call(elements,func);
Here you get the element handed over as first parameter in func.

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

JQuery multiple attributes in selection

I stumbled upon this form of selector. Notice the quotes, its two attributes.
$('#item1','#item2')
It seems to return only first element, which is different from $('#item1, #item2') result. I couldn't find any documentation on what exactly this does. Can somebody explain this or link to documentation with examples please
It's called context, and it's the same as find(), so this:
$('#item1','#item2')
would equal :
$('#item2').find('#item1');
in other words, it searched inside #item2 for an element with the ID #item1
To select both elements with ID's #item1 and #item2, you would do:
$('#item1, #item2')
notice the difference in quotes.
Selector in Jquery $(param) supports single string parameter and then it split parameter string and then do work for selecting element..
$('#item1','#item2') //treat first one param
$('#item1,#item2') //treat one param and splits passed string and will select both
You can specify any number of selectors to combine into a single result.
This multiple expression combinator is an efficient way to select disparate elements.
multiple-selector
multiple-selector-2
var list = $("div,p,span").map(function () {
return this.tagName;
}).get().join(", ");
$("b").append(document.createTextNode(list));

Can JQuery and Javascript be mixed together?

I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}

Categories

Resources