0

I'm trying to use data attributes to get some javascript to work:

$('div#here').data('added', 'this was added');

const initial_actual = $('div#here').data('initial');
$('div#initial').text(initial_actual)
const initial_css_found = $('div#here[data-initial="this was already here"]');
$('div#initial').append(initial_css_found.length)


const added_actual = $('div#here').data('added');
$('div#added').text(added_actual);
const css_found = $("div#here[data-added='this was added']");
$('div#added').append(css_found.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="here" data-initial='this was already here'>
  div
</div>

<div id='initial'>
 dive
</div>

<div id='added'>
 dive
</div>

basically if I set data attributes dynamically using jquery, these don't seem to behave similarly to similar data attributes that were present in the html when loading the page.

  • inspecting the generated HTML with my browser (Brave) the programmatically added data fields are not visible. enter image description here
  • if I retrieve the data from a jquery object, the data contained is present.
  • if I use a data selector (as found here) to get the element with the added data field, I get zero results
Don Giulio
  • 2,946
  • 3
  • 43
  • 82

1 Answers1

0

ok, as the manual of jquery mentions here,

Using the data() method to update data does not affect attributes in the DOM.
To set a data-* attribute value, use attr.

so the solution is as follows:

$('div#here').attr('data-added', 'this was added');

const initial_actual = $('div#here').data('initial');
$('div#initial').text(initial_actual)
const initial_css_found = $('div#here[data-initial="this was already here"]');
$('div#initial').append(initial_css_found.length)


const added_actual = $('div#here').data('added');
$('div#added').text(added_actual);
const css_found = $("div#here[data-added='this was added']");
$('div#added').append(css_found.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="here" data-initial='this was already here'>
  div
</div>

<div id='initial'>
 dive
</div>

<div id='added'>
 dive
</div>
Don Giulio
  • 2,946
  • 3
  • 43
  • 82