0

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 }.
4
  • 1
    I don't think that is possible using plain javascript but you can use custom data attributes to get something similar. Commented Apr 25, 2020 at 5:22
  • Thank you @palaѕн for response Commented Apr 25, 2020 at 7:19
  • If you want I can share an example using custom data attributes as an answer to help you get an idea. Commented Apr 25, 2020 at 7:21
  • I'm curious about this, please help me thank you Commented Apr 28, 2020 at 6:34

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.