Alexander Abramovich
Alexander Abramovich

Reputation: 11438

Search an DOM element by attribute name

How can I search (using jQuery) for a DOM element that has an attribute with a given name (not by attribute value)?

For example:

<div id="div1">
  <div id="div2" myattr="myvalue">
  </div>
</div>

I would like to search for every element under #div1 (inclusive) that has has an attribute named myattr (so that #div2 element will be returned).

Upvotes: 0

Views: 221

Answers (2)

Farhan Ahmad
Farhan Ahmad

Reputation: 5198

Use this selector:

$('#div1[myattr], #div1 [myattr]')

This will look for all #div1 with the attribute myattr and items under #div1 that has an attribute named myattr.

Documentation

Upvotes: 2

Jamiec
Jamiec

Reputation: 136074

You can use jQuery for that:

$('#div1 [myattr]')

This will find any element under #div1 which has a myattr attribute (with any value).

As pointed out by a commenter, this would not include div1. So update the selector to:

$('#div1[myattr], #div1 [myattr]')

Upvotes: 4

Related Questions