1

I want to access custom option attribute value but I am failed and I am not able to resolve my problem, could someone please help me to achieve my goal?

Code

<option value="1" data-set="demo">Value 1</option>

I want to access data-set value in console how it would be possible please help me?

5
  • How are you trying to access the attribute exactly...? Commented Feb 21, 2020 at 19:06
  • actually , I need to access custom attribute @entiendoNull Commented Feb 21, 2020 at 19:12
  • In React, you would want to use props instead of using data-* attributes. Could you elaborate your use case? Commented Feb 21, 2020 at 19:15
  • @Jonas : there's a surprisingly easy solution of your problem, You might want to check that out below. If it solves your problem upvote and accept are greatly appreciated ;) Commented Feb 21, 2020 at 21:36
  • Either you really are talking about React, in which case: your code generates those options, so you already have all those values available to you. Or, you're trying to get attributes from an HTML element, having nothing to do with React itself. In that case: you get them the same way we get attributes from any other HTML element. Find the element using any of the query functions (querySelector, getElementById, getElementsByTagName, etc. etc.) and then use e.getAttribute("blah") for plain attributes, or e.dataset.blah for data attributes. Commented Feb 21, 2020 at 21:45

4 Answers 4

5

If you have a handleChange event on the select, for example with two way binding then you can access it like so:

handleChange = (e) => {
   console.log( e.target.selectedOptions[0].getAttribute('data-set') );
}

In the render it might look like:

<select value={this.state.value} onChange={this.handleChange}>
Sign up to request clarification or add additional context in comments.

2 Comments

e.target will point to <select> node which doesn't have data-set properties at all, so your code will return undefined. The proper way to do the job is a bit different
Good spot! It's simply a case of e.target.selectedOptions[0].
3

onChange() event handler has access to selected options elements (single for regular <select>) through event.target.selectedOptions

In order to get data-set attribute you may leverage data-* API. In a nutshell, it provides access to data-* attributes through .dataset property of HTMLElement (hence, data-set value is accessible via .dataset.set):

So, with a bit of destructuring, your task may be solved as easy as that:

const { render } = ReactDOM

const Select = () => {
  const onChangeSelectedOption = ({
    target: {
      selectedOptions: [{
         dataset: {set}
      }]
    }
  }) => console.log(set)
  return (
    <select onChange={onChangeSelectedOption}>
      <option selected disabled>Select...</option>
      <option value="1" data-set="demo1">Value 1</option>
      <option value="2" data-set="demo2">Value 2</option>
      <option value="3" data-set="demo3">Value 3</option>
    </select>
  )
}

render (
  <Select />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

1 Comment

Thanks, it working but how I will access value like ( e.target.selectedoptions) I mean this way I want to access data-set value
0

const val = document.querySelector("option[value=\"1\"]").getAttribute('data-set')
console.log(val)
<option value="1" data-set="demo">Value 1</option>

or

const val = document.querySelector("option[value=\"1\"]").dataset.set
console.log(val)

2 Comments

what it does querySelector("option[value=\"1\"]")
It is perfectly fine to use querySelector() in plain JS or or similar stuff that attempts to access DOM nodes directly, but in React it may give unexpected results due to asynchronous updates of states and corresponding re-renders, so, there's another proper way to do that in React
0

If you are using the onChange handler function. Then you can get the value of the data-'format' easily. You are just required to pass on the event parameter. Then we have a dataset property using which we can get all the data-'format' declared in that tag. Dataset gives back a key value pair object containing custom attribute and its value.

const inputtag=document.getElementById("input_value")

const handleChange=(e)=>{

const customAttributes=e.target.dataset
/*customAttributes containes the attributes you defined, in key value pair*/

console.log(customAttributes)

/* example 
customAttributes = {
  "input": "value1",
  "value": "value2"
}
  

*/
}

inputtag.addEventListener('change',handleChange,true)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <input id='input_value' data-input='value1' data-value='value2' type='text' placeholder='write here'/>
</body>
</html>

Note, we can get custom attributes data using onClick function too, all the logic will stay as it is.

In case of input tags, we can prefer onChange while we can use onClick for other tags.

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.