tlq
tlq

Reputation: 35

How to find a tag which has a data attribute

I am trying to find the tag which has data-direction attribute. Somehow it is always undefined. What I am trying to do is get the values of data-direction and data-cellId. Any ideas?

var row = $('<tr data-cellId="' + cell.fatherId + '" data-direction="' + cell.direction + '"/>');
var nameColumn = $('<td class="port-name-col" data-cellId="' + cell.fatherId + '">' +cell.value.name + '</td>');
var btnColumn = $('<td class="port-btn-col"><button type="button" title="Remove" class="btn btn-default btn-xs x-button-icon btn-delete-port"><span class="glyphicon glyphicon-trash"></span></button></td>');
row.append(nameColumn);
row.append(btnColumn);

EventListener

$(document).off('click', '.btn-delete-port').on('click', '.btn-delete-port', function (event) {
    var elem = event.target || event.srcElement;
    //find tr element that has cellID attribute
    var tr = $(elem).find("tr.data-cellId");
    alert($(elem).parent().parent().html())
});

Upvotes: 2

Views: 135

Answers (1)

Stephan Muller
Stephan Muller

Reputation: 27630

The problem lies in this line:

var tr = $(elem).find("tr.data-cellId");

The .data-cellId part selects based on an element with that class. To look for an attribute, use [data-cellId] in your selector:

var tr = $(elem).find("tr[data-cellId]");

To then get the value of that attribute, you can use:

tr.attr('data-cellId');

Upvotes: 9

Related Questions