-1

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?

user687554
  • 10,663
  • 25
  • 77
  • 138
  • Use `document.querySelector` instead of jQuery so that you're not having to do an expensive search of the entire DOM only to get the first element. `document.querySelector('[data-custom-property]');`. –  Aug 23 '16 at 15:13
  • ...if you happen to know that it's a `div`, then using that in the selector will improve performance too. `div[data-custom-property]` Also, you can search from `document.body` instead of `document` if you *know* that element will be within the `body`. –  Aug 23 '16 at 15:14

1 Answers1

0

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")
Jesse Sierks
  • 2,258
  • 3
  • 19
  • 30