0

I am learning javascript and trying to store the value 2 in data-value in img element, and when I press the image I want to use javascript to show that value(2) in a paragraph. Here's my code:

<!DOCTYPE html>
<html>
<head>
<script>
 function ispisi() {
    var x = document.getElementById("myimage").data-value;
    document.getElementById('demo').innerHTML = x;
 }
</script>
</head>

<body>

<img id="myimage" data-value="2" onclick="ispisi()" src="bulboff.gif" width="100" height="180" />

<p id="demo">Text here<p>

</body>
</html>

The value should show in paragraph p, but when I click the image "text here" stays, insted. Why is this code not working?

2 Answers2

2

try this

var x = document.getElementById("myimage").dataset.value;

OR

var x = document.getElementById("myimage").getAttribute("data-value");
Sergey
  • 494
  • 2
  • 6
0

The proper way to do this would be as follows:

function ispisi() {
    var x = document.getElementById("myimage").getAttribute('data-value');
    document.getElementById('demo').innerHTML = x;
}

window.onload = function() {
    document.getElementById('myimage').onclick = ispisi;
};
wjohnsto
  • 4,323
  • 2
  • 14
  • 20