0

Is there any way to add data (that is not a class, id or value) inside the < > selectors of a div?

Say I have something like this

<div class="selection">normal html</div>

That I need to turn into something like this, inserting a data-use-type="STRING" value:

<div class="selection" data-use-type="STRING">normal html</div>

I can't edit the html directly, so javascript would be the perfect solution for it. And I know how to use the append function, but it does not work for what I want, I think... Can prepend work that way?

  • 1
    RTD: https://api.jquery.com/attr & https://api.jquery.com/data. Use the latter unless you explicitly need the attribute to appear in the DOM – Rory McCrossan Sep 30 '22 at 13:49

2 Answers2

1

You can set properties on the dataset of the element.

const div = document.querySelector('div');
div.dataset.useType = "STRING";
console.log(div.outerHTML);
<div class="selection">normal html</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Pure JavaScript solution

let div = document.getElementsByClassName("selection")[0]
div.setAttribute("data-use-type","String")
console.log(div)
<div class="selection">normal html</div>
flyingfox
  • 13,414
  • 3
  • 24
  • 39