98

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

204

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.

Sign up to request clarification or add additional context in comments.

5 Comments

If there are multiple p tags with custom attribute and I want to select which is inside specific div?
@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]').
I have done something like this. $('#parent_div').find('[data-action^="click-target"]'). Thanks
another solution would be to use this $("[id=choose]")
@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.)
12

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.