I have several classes that I want to select .group1-1 .group1-2 .group1-3, each one of these has 50 elements under it.
Is there a way to select all classes that start with group1 (so I end up selecting group1-1, group1-2, group1-3), something like $(".group1"+*)
You can also use something along the lines of this if you'd like to avoid regex:
$("[class^='group1-']").click(function () {
var groupNumber = $(this).attr('class').split('-')[1];
alert('Yep, you clicked group1-' + groupNumber);
});
Example here: http://jsfiddle.net/iwasrobbed/7bjtb/
This question discusses jquery wildcard / regex selectors. Which basically allow you to use a regular expression to specify matching classes.
Related
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.
I need to select an attribute in my code that match a string+number in the class name, using jQuery
What I need to do is to match something like that:
var myVar = 'item';
$('#id [class="'+myVar+'\d+"]');
My code contain other classes starting by "item" as well, so I can't use the selector class^="item"
I found out different things on Internet, but nothing that match perfectly my requirement.
I found the jQuery extension ":regex" but I'm not allowed to use it. http://james.padolsey.com/javascript/regex-selector-for-jquery/
I found the use of "filter" as a function but this is horrible for the performance
jQuery filter selector, is this right?
I tried to do something but it's not even working:
$('#id *').filter(function() {
return this.className.match("/"+myVar+"\d/");
});
Do you have some better suggestions?
Thanks.
No you can't use \d with CSS/jQuery selectors.
I suggest you split the number out into another attribute like data-number or something. This way you can target the class easily and efficiently and still have the number available.
<span class="my-class" data-number="1"></span>
<span class="my-class" data-number="6"></span>
<span class="my-class" data-number="10"></span>
jQuery example
$.each($('my-class'), function () {
$(this).attr('data-number');
});
As #Asad mentions they can also be selected using $('.my-class[data-number="1"]').
How about:
$('#id [class*=' + myVar + ']').filter(function() {
return this.className.match(new RegExp('(^|\\s)' + myVar + '\\d+(\\s|$)'));
});
Check jsfiddle demo here.
The selector picks every descendant element of #id with myVar in a class name. Finally it filters them, leaving only those who have myVar followed by one or more of digits as the name of one of its classes.
Note: You probably aready know that, but it is worth warning anyway: you must prevent myVar from having chars with special meaning to selectors (which would mess the [class*=' + myVar + ']' selector) and to regexes (such as the string '[a-z]', which would make the regex match a range instead of the literal '[a-z]' -- in this case, it should be escaped, as '\[a-z\]').
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));
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery attribute selector for multiple values
I have this
$('input:radio[name=foo]').change(function() {
blah();
});
$('input:radio[name=bar]').change(function() {
blah();
});
Can I do something like this?
$('input:radio[name=foo||bar]').change(function() {
blah();
});
what If I had another one?
$('input:radio[name=foo||bar||foobar]').change(function() {
blah();
});
I can't use class which would be ideal as this is a custom framework (not mine) that
generates the HTML which is overriding my class. Also there is no id selector available
just the name attribute. I think I'm stuck doing separate functions but wanted to pose the question to see if anyone can think outside the box on this one.
Note: this project uses jQuery 1.3.2 and I can't upgrade just yet. And before you say anything, yeah I'm with you on upgrading...
There is no 'or' character, but you can use multiple selectors - you just separate them by commas:
$('input:radio[name=foo], input:radio[name=bar]').change(function() {
blah();
});
Or better yet, use a class selector as this is exactly what they were designed for.
Unfortunately there isn't a simple selector for or within [attr] selectors. You can use a comma (,) to separate your selections:
$('input:radio[name=foo], input:radio[name=bar]').change(...);
Or if your selection happens to be longer, you can use $.fn.filter:
$('#foo #bar #baz .fizz .buzz input:radio').filter('[name=foo], [name=bar]').change(...);
I recommend reviewing the entire list of jQuery selectors.
jQuery's $() function uses CSS selectors (nearly all of CSS3 plus a few of its own). Their syntax has nothing whatsoever to do with JavaScript's logical operators.
Neither CSS3 nor jQuery offer a "match any of these", so you use a selector group instead:
$('input:radio[name=foo], input:radio[name=bar], input:radio[name=foobar]').change(function() {
blah();
});
Another alternative is adding a new filter for regex:
http://james.padolsey.com/javascript/regex-selector-for-jquery/
Then you can do something like
$('input:radio:regex(name, ^(foo|bar|baz)$)')
Your proposed solution does work on newer versions of jQuery. You can chain filter onto your query, though ...
$('input:radio').filter("[name=foo],[name=bar]").change(function() {
blah();
});
View and play with the jsfiddle here
http://jsfiddle.net/NAgv5/1/