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

169
Views
How can i get custom data attribute

I can get the value of id but data-id shows this error,

Uncaught ReferenceError: id is not defined

My code,

<ul id="highscores"></ul>
<script>
var hst = document.getElementById("highscores");

var highScores = [
    { id: "1",name: "Maximillian", score: 1000 },
    { id: "2",name: "The second guy", score: 700 },
    { id: "3",name: "The newbie!", score: 50 }
];

function deleteById ( self ){
    console.log(self.id);
    console.log(self.data-id);
}
for (var i = 0; i < highScores.length; i++) {
        hst.innerHTML +=
        "<li >" +"<a data-id='test' id="+highScores[i].id + " href='#' onclick='deleteById(this)'>x</a>" +
        highScores[i].name +
        " -- " +
        highScores[i].score +
        "</li>";
    }
</script>
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Properties and attributes are two separate things. The data-id attribute you've defined does not automatically correlate to a property on that element. Similarly, e.g. an <input type="text"> can have a value attribute, but the value property on it does not necessarily give you the value of that attribute, as the value property is pointing to what's currently in the input, whereas the value attribute is its initial value. Try to detach these two concepts.

To answer your question, though; there are two ways. One is to use element.getAttribute('data-id'). This works for any attribute. However, data-* attributes get their own fancy way to read and write their values; the dataset property. For example, to access the data-id property, you can use element.dataset.id. Similarly, to access the data-foo-bar attribute, you can use element.dataset.fooBar.

TLDR: Use element.dataset.id or element.getAttribute('data-id')

about 4 years ago · Santiago Gelvez 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!