Home > front end >  How to add one tags attribute in another tag using javascript or jquery?
How to add one tags attribute in another tag using javascript or jquery?

Time:12-22

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.

CodePudding user response:

The OP should have a look into ...

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 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 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 });
#mycode code { background-color: #ddd; font-weight: bolder; }
<span
  id="mycode"
  data-attribute="code-one"
  data-message="Well Done Dear"
  data-number="5"
  data-status="Active"
>
  span with a lot of
  <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*">
    <code>data-*</code>
    global attributes
  </a>
</span>

CodePudding user response:

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;
  • Related