0

I am having a problem using the .data jQuery function for a HTML jQuery Object.

var test = $('<div><div class="abc123"></div></div>');
test.find('.abc123').data('please', 'change');

and test still hasn't changed at all

<div>
    <div class="abc123"><div>
</div>

But using the .text function

test.find('.abc123').text('TESTING');

works properly:

<div>
    <div class="abc123">TESTING</div>
</div>

Is there any way to make the data work on the test var?


Edit:

What i am expecting after running

test.find('.abc123').data('please', 'change');

is

<div>
    <div class="abc123" data-please="change"></div>
</div>
3
  • Are you expecting the HTML of .abc123 to change? Commented Jan 10, 2015 at 3:54
  • I am expecting it to show <div class="abc123" data-please="change"></div> Commented Jan 10, 2015 at 3:55
  • jQuery's .data() method doesn't change the attribute but is managed internally by jQuery. Commented Jan 10, 2015 at 3:57

1 Answer 1

3

Calling .data() on an element, whether created in HTML or in a JQuery object will not modify the associated markup. Regardless, the associated DOM properties are updated.

var test = $('<div><div class="abc123"></div></div>');
test.find('.abc123').data('please', 'change');

alert(test.find('.abc123').data('please'));

The above code will alert 'change'.

If your goal is to also update the markup, you could instead use:

test.find('.abc123').attr('data-please', 'change');
Sign up to request clarification or add additional context in comments.

1 Comment

Oh this is interesting, just checked this, and you are right! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.