Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Get custom attribute value from select

I'm trying to clone a select options into another select. At the moment I'm able to do it but now the original option contains a custom attribute. So my question is how can I access to the custom attribute? This is what I have for now:

var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
    var id = parseInt($(options[i]).val(), 10);
    var text = $(options[i]).text() || '[select a type]';
            
    arrayOptions.push('<option value="' + id + ' data-custom="' + options[i]["data-custom"] + '">' + text + '</option>');
    
}
console.log(arrayOptions);

<select id="sel1">
    <option value="1" data-custom="abc1">Hello 1</option>
    <option value="2" data-custom="abc2">Hello 2</option>
    <option value="3" data-custom="abc3">Hello 3</option>
</select>

Right now options[i]["data-custom"] is setting undefined instead of abc1, abc2, etc.

Here is a fiddle.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use dataset.custom

var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
    var id = parseInt($(options[i]).val(), 10);
    var text = $(options[i]).text() || '[select a type]';
                
    arrayOptions.push('<option value="' + id + ' data-custom="' + options[i].dataset.custom + '">' + text + '</option>');
}
$('#result').text(arrayOptions.join("\n"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
<option value="1" data-custom="abc1">Hello 1</option>
<option value="2" data-custom="abc2">Hello 2</option>
<option value="3" data-custom="abc3">Hello 3</option>
</select>
<pre id="result"></pre>

about 4 years ago · Juan Pablo Isaza Report

0

this way

const arrayOptions = 
  [...document.querySelectorAll('#sel1 option')]
  .map( opt => `<option value="${opt.id}" `
             + `data-custom"${opt.dataset.custom}">`
             + `${opt.textContent}"</option>`
      )
console.log(arrayOptions);
 <select id="sel1">
  <option value="1" data-custom="abc1">Hello 1</option>
  <option value="2" data-custom="abc2">Hello 2</option>
  <option value="3" data-custom="abc3">Hello 3</option>
</select>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!