llanato llanato - 6 months ago 30
Javascript Question

jQuery, data() not updating data attribute

I have the below piece of HTML and the associated jQuery. The

html
function is working correctly but the
data
function isn't affecting the HTML at all, I can't for the life of me figure it out, no errors in the browser at all.

HTML

<span id="usernameStatus" data-valid="0">x</span>


jQuery

data
is returned by an AJAX call, it will only ever be
true
or
false
.

function validUsername(data)
{
if (data === 'true') {
$("#usernameStatus").html("y").data("valid", 1);
} else {
$("#usernameStatus").html("x").data("valid", 0);
}
}

Answer

Per jQuery API Docs

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

The .data() method will not modify the existing DOM node, but will only be retrievable via calling of $selector.data(). Your DOM elements don't change, just the data attached to them.