JQuery: 选择具有自定义属性的所有元素

可能的复制品:
JQuery,通过属性值选择,添加新属性
JQuery-如何通过属性 进行选择

请考虑以下代码:

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

如何选择具有 MyTag属性的所有 p标签?

谢谢

141405 次浏览

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.

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