user687554 user687554 - 3 months ago 18
jQuery Question

jQuery - Select First Element with a Custom Attribute

I have a web page. This web page has an area with some dynamically generated HTML. I want to get the first element (not all elements) within this area that has a custom attribute of a specific name. I then want to get that attribute value. I've setup a Fiddle. The code is like this:

<div id="myElement">
<div>
<div>
<ul>
<li></li>
<li><div data-custom-property="12345">
<p>
Some details
</p>
<div>
<div>
<div data-custom-property="xyzwt">
Stuff
</div>
</div>
</div>
</div></li>
<li></li>
</ul>
</div>
</div>
</div>

<button onclick="return getFirstElementWithProperty('data-custom-property');">
Get Element
</button>


Basically, I'm trying to get the first element within
myElement
that has the
data-custom-property
attribute. Everything I've seen (1, 2) involves looking for the value of an attribute. I want to search by name.

How do I find it?

Answer

If it will always be a div, and you know the element's ID:

$("#myElement div[data-custom-property]:first")

Otherwise, this will work, too, though it's best to be as specific as possible:

$("[data-custom-property]:first")