2

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

Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
KingFish
  • 8,773
  • 12
  • 53
  • 81
  • 1
    Possible duplicate http://stackoverflow.com/questions/1944302/jquery-select-an-elements-class-and-id-at-the-same-time – chiarfe Sep 02 '13 at 21:21
  • possible duplicate of [get element value using jquery](http://stackoverflow.com/questions/8555064/get-element-value-using-jquery) – Trikaldarshiii Sep 03 '13 at 00:44

4 Answers4

4

You can use:

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

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

Adrift
  • 58,167
  • 12
  • 92
  • 90
3

Try this

$("div.foo.bar[data-id='12345']");
Sachin
  • 40,216
  • 7
  • 90
  • 102
1

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)");
Charaf JRA
  • 8,249
  • 1
  • 34
  • 44
0

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;
    });
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66