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?

1
  • dashes are not legal in variable names, data-value means data minus value Commented Nov 10, 2014 at 2:17

2 Answers 2

2

try this

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

OR

var x = document.getElementById("myimage").getAttribute("data-value");
Sign up to request clarification or add additional context in comments.

Comments

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;
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.