skip to Main Content

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?

2

Answers


  1. Pure JavaScript solution

    let div = document.getElementsByClassName("selection")[0]
    div.setAttribute("data-use-type","String")
    console.log(div)
    <div class="selection">normal html</div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search