97

Possible Duplicate:
jQuery, Select by attribute value, adding new attribute
jQuery - How to select by attribute

please consider this code:

<p>11111111111111</p>
<p MyTag="nima">2222222222</p>
<p>33333333333</p>
<p MyTag="Sara">>4444444444</p>

how I can select All p tag with attribute MyTag?

thanks

1

2 Answers 2

202

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

5
  • 1
    If there are multiple p tags with custom attribute and I want to select which is inside specific div? Jan 17, 2017 at 10:10
  • 1
    @Jnana - Select the div first, then use .find() to get the p element inside it. Or combine the selectors, e.g., if the div has an id: $('#idOfDiv p[MyTag]').
    – nnnnnn
    Jan 17, 2017 at 21:23
  • I have done something like this. $('#parent_div').find('[data-action^="click-target"]'). Thanks Jan 18, 2017 at 5:49
  • another solution would be to use this $("[id=choose]")
    – code-it
    Nov 17, 2020 at 21:04
  • @code-it - I don't understand what you mean, that's the same syntax I put in my answer, except you're specifying an attribute not applicable to the OP's HTML. (And one wouldn't do that for an id attribute given the is a specific selector for that purpose.)
    – nnnnnn
    Nov 18, 2020 at 4:00
11

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

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