Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  45] [ 5]  / answers: 1 / hits: 23973  / 10 Years ago, fri, june 6, 2014, 12:00:00

Can jQuery or JavaScript be used with a regex to select multiple elements with similar id?



I have the following paragraphs:



<p id=item5_2> A </p>
<p id=item9_5> B </p>
<p id=item14_2> C </p>


I want to change the content of paragraphs with id starting in item and ending in 2.



I used the following jQuery:



$(#item[d]*2).html(D);


but it doesn't work. How can I get it to work?



JSFiddle Demo


More From » jquery

 Answers
15

Yes it can, you can combine the attribute starts with and the attribute ends with selector



$('[id^=item][id$=2]').html(D);


FIDDLE (and you have to enable jQuery in the fiddle)



you can't use regex to match the numbers in between though, for that you'd need filter()



$('[id^=item]').filter(function() {
return this.id.match(/itemd+_2/);
}).html(D);

[#70682] Thursday, June 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cartersinceren

Total Points: 442
Total Questions: 116
Total Answers: 106

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;