• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

121
Vistas
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 3 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

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 3 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda