can't use dynamic assigned data attribute in select

3540 views javascript
4

I have a div element with class ROW. I do a $.each($(".row) and assign a data-id attribute containing an unique id. But when I try to select the element it can't find id.

I can run $(".row").data("id") in debugger in Firefox and I get the correct value, but when I try to select $(".row[data-id='1']") it doesnt find any element and doesn't show any data attribute in Inspector in Firefox.

If I define data-id in the html it works as expected, but I need to assign the value dynamically.

Code:

<div class="row">
...
</div>

$.each($(".row"), function (i) {
    var $row = $(this);

    $row.data("id", i);
});

Select:

$(".row[data-id='1']"); //returns nothing

$(".row").data("id"); //returns 0 (expected)

answered question

Try $row.attr("data-id", i)

there aren't any .rows with a data-id attribute in your markup

Lucia Kiebel: no because it is set dynamically in $.each loop

@MartinAdámek that returned undefined. $row.data("id") works, but not when trying to select it using $(".row[data-id='1']")

Well if you have just one .row, then there is no data-id=1, as it starts from zero and the first one is data-id=0.

1 Answer

4

Use $.attr('data-id', ...) instead of $.data('id', ...).

Also note that you are trying to access element data-id=1, that does not exist if you have just one .row element.

$.each($(".row"), function (i) {
    var $row = $(this);
    $row.attr("data-id", i);
});

console.log($('.row[data-id=1]'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row">
1...
</div>

<div class="row">
2...
</div>

$.data will set internal data attribute value, while $.attr will add the attribute to DOM.

posted this

Have an answer?

JD

Please login first before posting an answer.