Corjava
Corjava

Reputation: 340

Targeting data attributes

I have a handful of buttons, and they are inside a couple divs like so:

<div id="inventory">
  <div>
     <button data-amount="1">Buy 1 @ $0.30</button>
     <button data-amount="4">Buy 4 @ $1.00</button>
     <button data-amount="30">Buy 30 @ $6.00</button>
     <button data-amount="140">Buy 140 @ $21.00</button>
  </div>
</div>

<div id="product">
  <div>                 
    <button data-amount="1">1</button>
    <button data-amount="10">10</button>
    <button data-amount="all">All</button>
  </div>
</div>

The problem is, is that most of the examples I've found on how to use this data attribute, has used something like this to target them.

$( "div" ).data( "amount" ) === "stuff";

My buttons are in different divs but are both using 'data-amount' I wanted to know if there was a way for me to instead of targeting divs in general, target the highest parent div for these buttons and retrieve the data values accordingly.

Upvotes: 1

Views: 121

Answers (1)

scrappedcola
scrappedcola

Reputation: 10572

You can get all of the div's with data-amount via:

var cont = $("#inventory").find("button[data-amount]");

or a specific one with

var cont = $("#inventory").find("button[data-amount=all]");

Upvotes: 2

Related Questions