Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select elements with id attribute that starts/ends with a particular value

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

like image 977
Alexandru Severin Avatar asked Jun 06 '14 12:06

Alexandru Severin


People also ask

Which selects elements that have the specified attribute with a value beginning exactly with a given string?

attributeStartsWith selector Description: Selects elements that have the specified attribute with a value beginning exactly with a given string.

How do you select an element with ID data '?

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.

How do I select multiple elements by ID?

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.

What is the value of an ID attribute?

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.


1 Answers

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"); 
like image 50
adeneo Avatar answered Sep 25 '22 00:09

adeneo