Sebastian Salines
Sebastian Salines

Reputation: 81

Return $(this) Dom Element jQuery

I'm trying to find an element by it's data-id and data-type so I can do stuff with it, but I'm finding an error when doing so.. Here's my function:

    find : function(id, type) {
    $('.elem').each(function(index, element) {
        if ($(this).data('id') == id && $(this).data('type') == type)
            return $(this);
    });
},

What I try to do for example is:

myClass.find(1, 'myType').text('whatever');

How can I do this?

EDIT: Thanks to adeneo and user3558931! Modified to:

    findPro : function(id, type) {
    return $('.elem[data-id=' + id + '][data-type=' + type + ']');
},

Upvotes: 0

Views: 195

Answers (2)

adeneo
adeneo

Reputation: 318182

find : function(id, type) {
    return $('.elem[data-id="'+id+'"][data-type="'+type+'"]');
},

as a sidenote, this won't work if the data was initially set with data(), I'm assuming these are HTML5 data attributes, as in

<div data-id="something" data-type="something else"></div>

and this is not chainable as it's not added to jQuery's prototype

Upvotes: 3

PeterKA
PeterKA

Reputation: 24638

In .each() return serves a completely different purpose. So you have to take a different approach:

......
findPro : function(id, type) {
    return $('.elem[data-id=' + id + '][data-type=' + type + ']');
},
.......

Upvotes: 1

Related Questions