HHHome HHHome - 1 year ago 225
Javascript Question

Jquery Data attribute selector not working

I have this element

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

is set dynamically like so:

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

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


Returns empty array. Interestingly:



What is wrong with my selector?

Answer Source

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/


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


// 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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download