JQuery multiple attributes in selection - javascript

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));

Related

what to know little about the arguments for given code .....?

$('.selector:contains("'+ filterText +'")').show()
for showing div based on the bases of string "search" now it's working fine with the exact character case of lowercase and upper case
now here i googled my issue many links i found and in almost all sites and event stackoverflow i found similar code like below code..
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())> -1;
};
so here i am interested in this a, i, and m parameters
also that how can i use the $(".selector":contains('"+ search +"')).show() with any case sensitivity ( lowercase or upper case ).
the use this code with what i have written will be better one
and alternative solutions about free text search with key press will be the best on but but but
no use of third party plugins.
i think You guys need to refer bellow link
http://jsfiddle.net/potherca/ympBL/
There are many ways to filter an element that contains the give text. One form is the following.
$(".selector:contains('"+ search +"')").show();
But this is case sensitive. If you'd like a case insensitive match, you may want to write a custom filter method by extending the filter expressions of jQuery, like below.
jQuery.extend(jQuery.expr[':'], {
icontains: function(elem, index, arr){
return jQuery(elem).text().toLowerCase().indexOf(arr[3].toLowerCase()) !== -1
}
});
In the method you create for any jQuery expression, you are given three arguments. The first is the DOM element for that particular iteration. Second is the index of the DOM element relative to the original collection the expression was called on. Last is an array similar to what you'd get from a RegExp exec method call. The full expression is the first array position, second is the text from the selector between the colon and opening paren, and the last is the string that occurs within the parens.
Then use it as:
$(".selector:icontains('" + search + "')").show();
I would suggest you learn to use filter(fn) which offers lots of control over how you filter elements.
$(".selector").filter(function(){
return $(this).toLowerCase().indexOf(search.toLowerCase()) >-1;
}).show();

regex that matches and captures headings

I've got this Regex /<h([2-4])>(.+)<\/h[2-4]>/g
It matches all h2,h3,h4 and captures the level and heading-text.
Is it good enough or do you see room for improvement in terms of speed and robustness?
Do not use regex on HTML. You can use Element.querySelectorAll. Replace Element with a reference to the DOM-element from which you like to select the headings.
var heading = document.querySelectorAll("h2, h3, h4");
QuerySelectorAll (and his brother querySelector) use CSS selectors to select elements from the DOM. You can supply multiple selectors using commas. This will select all h2-4 elements. You can loop them with this code:
Array.prototype.map.call(heading , function(element){
//do something with the element here.
console.log(element.textContent); //EXAMPLE, display the text in the element.
});
Since querySelectorAll returns a node list (which is an arrayish object) we can pass it to Array.map (though not directly). We use Array.prototype.map.call to pass the node list to the map function as array. Map loops over every element in the node list.
Make your regex to do a non-greedy match. And also make the regex to do back-referencing.
/<(h[2-4])>([^<>]+)<\/\1>/g
OR
/<(h[2-4])>((?:(?!<h\d+\b).)+?)<\/\1>/g
DEMO

Why does the order of the selectors in a queryselector call matter?

I think i may have found a bug in the querySelector function. It seems that the order the selectors are placed affects whether or not the selectors are selected.
I'm trying to select a link using querySelector, and am passing in 3 different selectors, and would like it to select any one of those 3, unfortunately, sometimes it won't match the selector even when there is a definite match on the page, unless I rearrange the order of the selectors in the querySelector function.
Test link that i want to match:
<span>#Coyotes</span> 60 recent posts
This function returns null:
document.querySelector("a[href$='?source=fttp']","a[href$='?source=ftp']","a[href^='/topic/']")
This function call matches the link
document.querySelector("a[href$='?source=ftp']","a[href^='/topic/']","a[href$='?source=fttp']")
both calls have the exact same selectors, only in a different order
I've created a jsfiddle that demonstrates the problem:
http://jsfiddle.net/eB8nv/5/
Can anyone tell me what is going on here, and why the order of the selectors sent to the querySelector function matters?
querySelector() only takes one parameter.
You can't do that.
Instead, you need to pass a single string with three comma-separated selectors.

Select class name (number) using RegEx & Jquery

I have a element like this
<div class="th-class2 th-hhjjsd th-context-78474378437834873"></div>
(Note: I know class names should not be pure numbers)
I want to get the numerical number from this div.
id = 78474378437834873
Is there a way I can use regular expressions to do it. I am nearly there but it only returns the first 4 numbers.
I use a clickevent to target the div and try and get the class like this
var classString = $(this).prop("class").match(/([0-9]+)/)[1];;
console.log(classString)
result is 7847
I am just not understanding how to get the rest of the number.
Thanks
You shouldn't use integers for class names because using a class typically means you are going to use the element more the once and adding a dynamic number defeats the purpose of classes, also working with someone else code and they use integers it's very hard to understand their code. As far as your questions goes, you shouldn't really use regular expressions to get a value of a class you should either store the value as an id so your element would look like this,
HTML
<div id="78474378437834873" class="th-class2 th-hhjjsd"></div>
or you could use a data object which is how I would do it like so,
HTML
<div class="th-class2 th-hhjjsd" data-object='{"value":78474378437834873}'></div>
and then when you select your element with your click event to get the value of the element you clicked console log the elements data object like so
jQuery
$('.th-class2').click(function() {
console.log($(this).data('object').value);
});
You should not use number only class names, they must start with an Alpha character [a-Z]
You can find what are the allowed characters in this discussion: Which characters are valid in CSS class names/selectors?
(Please make sure to read also the comments).
As per a solution for you,
The easy solution would be to use data attributes as so:
<div data-id="1000"></div>
and then you could get your id as simple as:
$(this).on('click', function() { console.log($(this).data('id')); } );
Happy Coding.

Combining selectors as variables in jQuery

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

Categories

Resources