I want to know that, is it possible to bypass one tags data-attribute into another tag using javascript or jquery ?
For example, if I write this tag <span id="mycode" data-attribute="my-code"></span>
in anywhere inside body, the data-attribute tag will be append automatically in body tag <body data-attribute="my-code"></body>
When I create a template, the <body>
tag is without any attribute. I want that, when I’ll write this tag with attribute (<span data-attribute="my-code">
), only the attribute will be add in body tag (<body>)
.
If somebody know, please help me.
2
Answers
You can access
data-XXX
attributes using thedataset
property. Then simply assign from one element to another.The OP should have a look into …
Object.assign,
an
HTMLElement
‘sdataset
propertyand into e.g.
querySelector
from the selector API.The
Object.assign
based approach used by the beneath provided example code merges thedataset
object of the second provided source-element …document.querySelector('#mycode')
… into thedataset
object of the first provided target-element …document.body
. Which means that every property of the former gets assigned as property to the latter thus also overwriting equally named already existing properties.Notes
?.
is the Optional Chaining Operator, which allows chained property access in a fail safe way (in case properties do not exist).??
is the Nullish Coalescing Operator which here gets used for falling back to a default value in case the left hand side value is eithernull
orundefined
.