SpaceNinja
SpaceNinja

Reputation: 512

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:

$('[data-user="joe"]')

But that selected both the top two buttons.

Bonus points: "joe" comes in as a variable. So I'm dealing with:

var userNameFromForm = "joe";
$('[data-user="'+userNameFromForm+'"]')

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.

Upvotes: 1

Views: 70

Answers (3)

Josh Crozier
Josh Crozier

Reputation: 241128

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:

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

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();

Upvotes: 4

Jobelle
Jobelle

Reputation: 2834

var userNameFromForm = "joe";

        //$('.btn-edit[data-user=' + userNameFromForm + ']') element that you want

        $('.btn-edit[data-user=' + userNameFromForm + ']').css('color', 'red')

Upvotes: 1

domdomcodecode
domdomcodecode

Reputation: 2453

As Josh Crozier mentioned, you could try using the :first selector, but I wouldn't recommend that unless you're certain the order of the buttons don't change. I'd probably recommend using more selectors or adding ID's to your buttons.

For instance, you can also target the class name btn-edit since I can see they're unique within your snippet:

$('.btn-edit[data-user="joe"]')

But the safest would be to use unique names as an ID attribute:

<button id="edit" class="btn-edit" data-user="joe"></button>

$('#edit')

Upvotes: 1

Related Questions