Alex
Alex

Reputation: 1042

How do you select all id tags that contain a certain string in javascript?

I have an ASP.NET application that renders multiple questions with the option to provide an explanation for the answers given.

<label for="[<%:count %>].AnswerExplanation_<%: i+1 %>" id="[<%:count %>].toggleExplanation_<%: i+1 %>"><strong>Add Explanation</strong></label>
<br /><br />
<div id="[<%:count %>].Explanation_<%: i+1 %>">
    <textarea id="[<%:count %>].AnswerExplanation_<%: i+1 %>" name="[<%:count %>].AnswerExplanation_<%: i+1 %>" class="ckedit"></textarea>
</div>

so you will have id's like "[X].toggleExplanation_Y" corresponding to "[X].AnswerExplanation_Y"

I am writing a javascript function to show/hide the AnswerExplanation divs, and was looking for a way to select every id containing "toggleExplanation" I should be able to get the rest from there.

Upvotes: 19

Views: 52288

Answers (3)

Leon
Leon

Reputation: 3401

Give all the .toggleExplanation_ divs a unique marker CSS class. Then you can simply use jQuery to select all elements with that class.

Upvotes: 1

Niels
Niels

Reputation: 49919

If your using jquery you can use this to select everything containing "toggleExplanation"

$("[id*='toggleExplanation']") 

Upvotes: 21

John Hartsock
John Hartsock

Reputation: 86872

Try using the attribute contains collector

$('label[id*="toggleExplanation"]')

Upvotes: 31

Related Questions