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
attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet.
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(/item\d+_2/); }).html("D");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With