user687554 user687554 - 1 year ago 104
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">
<li><div data-custom-property="12345">
Some details
<div data-custom-property="xyzwt">

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

Basically, I'm trying to get the first element within
that has the
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 Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download