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.
The OP should have a look into...
an HTMLElement
's dataset
property
and into eg querySelector
from the selector API.
The Object.assign
based approach used by the beneath provided example code merges the dataset
object of the second provided source-element... document.querySelector('#mycode')
... into the dataset
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 save 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 either null
or undefined
.
console.log('before...', { body: document.body }); Object.assign( document.body.dataset, document.querySelector('#mycode')?.dataset?? {} ); console.log('after...', { body: document.body });
<span id="mycode" data-attribute="code-one" data-message="Well Done Dear" data-number="5" data-status="Active" >span with a lot of global <code>data-*</code> attributes</span>
You can access data-XXX
attributes using the dataset
property. Then simply assign from one element to another.
document.body.dataset.attribute = document.getElementById("mycode").dataset.attribute;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.