Can jQuery or JavaScript be used with a regex to select multiple elements with similar id?
I have the following paragraphs:
Here is the working JS FIDDLE
HTML:
<p id="item5_2"> A </p>
<p id="item9_5"> B </p>
<p id="item14_2"> C </p>
<input type="button" value="Get element ids starting with 'item' and ending with '2'" onclick="get_ids()">
JS:
get_ids = function(){
$('[id^="item"][id$="2"]').each(function() {
alert($(this).attr('id'));
});
}
You can use "start with" and "ends with" selectors provided by jQuery, like below.
$("[id^='item'][id$='2']").html("D");
Official documentation:
You can combine attribute selectors: fiddle
$("[id^='item'][id$='2']").html("D");
The best way to go is to use the following jQuery selectors
^= is starts with
$= is ends with
= is exactly equal
!= is not equal
*= is contains
So in your case:
var $items = $('[id^="item"][id$="2"]');
You can use next code if you want to do any other action:
$('[id^="item"]').each(function(){
if(this.id.slice(-1) == 2){
//Do something
$(this).html('D');
}
});
Try this
<p id="item5_2"> A </p>
<p id="item9_5"> B </p>
<p id="item14_2"> C </p>
and...
$('[id^="item"][id$="2"]')