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>
CodePudding user response:
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')