Peep Peep Peep
Peep Peep Peep

Reputation: 151

How to create/get custom attribute element in html by javascript?

I have element same below:

<div cutomsAttr.option1.option2="abc" id="custom">
</div>

I want to create and get custom attribute containing modifiers, if any.

For example in cutomsAttr.option1.option2, the modifiers object would be

{ option1: true, option2: true }.

Upvotes: 0

Views: 58

Answers (1)

palaѕн
palaѕн

Reputation: 73906

You can use data-* attributes, which allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes or extra properties on DOM.

The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Lets say you have a div and you want to store some extra information that doesn't have any visual representation. Just use data attributes for that like:

<div id="custom" data-cutomsAttr="abc">
</div>

Then in your code, you can access its new data-cutomsAttr attribute value dataset property like:

const custom = document.querySelector('#custom'); 
console.log( custom.dataset.cutomsattr )
<div id="custom" data-cutomsAttr="abc">
</div>

Note: That camelCase attribute cutomsAttr are converted to lowercase cutomsattr.


Now, in order to get something solar to "Custom attribute containing modifiers", you can just set multiple data attributes for the options like:

<div id="custom" data-cutomsAttr="abc" data-option1="true" data-option2="false">
</div>

and then access them like:

const custom = document.querySelector('#custom'); 
const { cutomsattr, option1, option2 } = custom.dataset
console.log( cutomsattr, option1, option2 )
<div id="custom" data-cutomsAttr="abc" data-option1="true" data-option2="false">
</div>


In case, if you don't want to set data-option1 & data-option2 all divs and make them optional with default value false, you can also do that like:

const custom = document.querySelector('#custom'); 
const { cutomsattr, option1 = false, option2 = false } = custom.dataset
console.log( cutomsattr, option1, option2 )
<div id="custom" data-cutomsAttr="abc" data-option1="true">
</div>

Upvotes: 1

Related Questions