72

I have a group of buttons on my web page which all have an id that end with the text "EditMode".

I'm using jQuery to assign an event to like so

$('[id $=EditMode]').click(editHandler);

However now I want to prefix the id with a name (which I will know in advance) so the id would be "aName+someotherstuff+EditMode". How do I alter the above expression so I match on aName AS WELL as editMode?

2 Answers 2

160
$('[id ^=aName][id $=EditMode]')
2
  • 2
    I would always just add quotes around your selector name like so $('[id ^="aName"][id $="EditMode"]') See fiddle for working example jsfiddle.net/u6mzs720
    – Phil Cook
    May 30, 2018 at 12:45
  • This works great for filling ASP BeginCollection elements via javascript. Feb 20, 2020 at 16:43
13

Alternatively, you can use the "add()" function for readability, but I would recommend Chaos's method:

$("[id ^=aName]").add("[id $=EditMode]")
1
  • 1
    Actually this answer does not achieve the same as chaos answer. This selects all elements with id's beginning with 'aName' and all id's ending with 'EditMode'. Chaos' answer would select all elements that both begin 'aName' and end 'EditMode' within each id. I used this 'for readability', before realising my mistake, as I was selecting input fields and the square braces are a little confusing. If it helps any one else that is written like: $("input[name^='start_term']input[name$='[end_term]']")
    – dading84
    Dec 18, 2016 at 22:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.