KingFish
KingFish

Reputation: 9183

jquery get element by attribute and class

If I have an element:

<div>
     <div class="foo bar" data-id="12345"></div>
     <div class="foo bar" data-id="678"></div>
     <div class="foo bar" data-id="910"></div>
</div>

How can I get the element with data-id="12345" and class="foo bar" ?

Thanks

Upvotes: 3

Views: 4820

Answers (4)

Adrift
Adrift

Reputation: 59859

You can use:

$('[data-id=12345].foo.bar').css('color', 'peru');

http://jsfiddle.net/LBqhP/1/

Upvotes: 5

nbrooks
nbrooks

Reputation: 18233

Chain the class selectors, then filter based on the data parameter:

$(function() {
    $("div.foo.bar").filter(function() {
        return $(this).data("id") == "12345";
    });
});

jsFiddle Demo
You can also easily wrap this logic into a reusable and extensible function:

function getDivWithDataId(id) {
    return $("div.foo.bar").filter(function() {
        return $(this).data("id") == id;
    });
}

which returns the jQuery collection matching the relevant div elements.

You can extend this to include classes (by passing an array of classes, like ['foo','bar']):

function getDivWithDataId(id, classes) {
    return $("div").filter(function() {
        var $self = $(this);
        var classMatch = true;

        $.each(classes, function(idx, val) {
            if (!$self.is(val)) classMatch = false;
        }

        return $(this).data("id") == id && classMatch;
    });
}

Upvotes: 0

Charaf JRA
Charaf JRA

Reputation: 8334

If you want to access your div that has class='foo bar' and data-id=12345 :

var element = $("div.foo.bar[data-id=12345]"); 

If you want simply to access the first div element that has class='foo bar' :

var element =  $("div.foo.bar:nth-child(1)");

Upvotes: 1

Sachin
Sachin

Reputation: 40990

Try this

$("div.foo.bar[data-id='12345']");

Upvotes: 3

Related Questions