Select an element by class IF it has this particular data-attribute (jQuery)

Consider this HTML:

<button class="btn-edit" data-user="joe"> Need to select this. </button>
<button class="btn-cancel" data-user="joe"> Not this. </button>
<button class="btn-edit" data-user="sally"> Not this. </button>
<button class="btn-cancel" data-user="sally"> Not this. </button>

I’d like to select the first button - Joe’s edit button. Basically of all the edit buttons, I want to select the one that matches the data-attribute that I have.

I got this far:


But that selected both the top two buttons.

Bonus points: “joe” comes in as a variable. So I’m dealing with:

var userNameFromForm = "joe";

But that’s nutty so I’ll be happy with an answer to the original question, or suggestions on how best to refactor this if I’m off in the wrong direction.


Add the class selector, .btn-edit, and then either use the :first selector, or the .first() method to select the first element in the jQuery object:

// or

The same applies to the version with the variable:

var userNameFromForm = "joe";

$('[data-user="' + userNameFromForm + '"].btn-edit:first');
// or
$('[data-user="' + userNameFromForm + '"].btn-edit').first();