Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Data attribute selector not working

I have this element

<div class="messages selected" data-conversationId=""></div>

The data-attribute conversationId is set dynamically like so:

$(".messages").data("conversationId", conversationId);

I am having issues using a selector to select this element by the data attribute.

$(".messages[data-conversationId=4]")

Returns empty array. Interestingly:

$(".messages").data("conversationId")

returns 4

What is wrong with my selector?

like image 384
Nick H Avatar asked Oct 18 '16 17:10

Nick H


People also ask

How get data attribute value in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How add data attribute in jQuery?

Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.

How to access data attribute?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to "5" .

How to get value of data attribute in js?

We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.


1 Answers

If you set your dynamic attribute via jquery's .data() you will have the above problem.

However, if you set the dynamic attribute via jquery's .attr() method, you won't have this problem

Example here: https://jsfiddle.net/6dn5wjL8/8/

HTML

<div id="test1" class="messages selected" data-conversationId="">testContent1</div>
<div id="test2" class="messages selected" data-conversationId="">testContent2</div>

JS:

// Will work
$("#test1").attr("data-conversationId", 4)
// Will not work
$("#test2").data("conversationId", 3)


alert("With selector .messages[data-conversationId=4] I found a div with this content: "+$(".messages[data-conversationId=4]").html())

alert("With selector .messages[data-conversationId=3] I found a div with this content: "+$(".messages[data-conversationId=3]").html())
like image 125
Boieriu Alexandru Avatar answered Sep 25 '22 07:09

Boieriu Alexandru