3

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

2

4 Answers 4

5

You can use:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I love that there's a colour called 'peru'
3

Try this

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.