Search code examples
javascripthtmlcustom-data-attribute

Set data attribute based on text of element?


Is it possible to set the value of a data-* attribute based on the text of the HTML element? Schematically, this is what I have in mind:

<div data-text={this.text}>example</div>

resulting in data-text="example".

I think it may be possible if you set an id and then get the element by that, like this:

<div id="exampleId" data-text={document.getElementById("exampleId").textContent}>example</div>

But this is not what I'm hoping for because it requires setting an id ahead of time (so may as well just set the data attribute ahead of time). What I'm aiming for avoids the need to set anything specific to the element ahead of time and uses a property of the element itself to set that.

Maybe this isn't even a well defined question! But figured I'd ask. Thanks in advance :)


Solution

  • You could use querySelectorAll and apply logic to each element that has a data-text attribute like this:

    const elements = document.querySelectorAll("[data-text]")
    
    elements.forEach(element => {
        element.setAttribute("data-text", element.innerText)
    })