1

i'm trying to get the value from the ID => vname into the variable name

and the return should be "Loren", I tried with and without the value attribute call but doesn't work. what am i missing?

<html>
<head>

<script>
var name = document.getElementById("vname").value;


alert(name);


</script>
</head>

<body>
<p id="vname" value="firstname">Loren</p>


</body>
</html>
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
myrith84
  • 21
  • 4

4 Answers4

4

There are three things wrong here:

  • You are trying to access the element before it exists You cannot eat the pizza before it is delivered... See Why does jQuery or a DOM method such as getElementById not find the element? for more info.

  • <p> HTML elements do not have a value attribute. In your case, value is a non-standard HTML attribute. If you want to use custom attributes, use data-* attributes instead.

  • p DOM elements do not have a value property. Only form control elements (input, select, etc) have such a property. If you want to get the content of an element, use innerHTML or textContent instead.


If you had opened your browser's console, you would have seen an error, because the element with ID vname couldn't be found. Make yourself familiar with your browser's developer tools so that you can fix issues like this on your own.

Community
  • 1
  • 1
Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
1

You can't get the "value" of a p element, you have to get the "innerHTML"

try this: var name = document.getElementById("vname").innerHTML;

Léo
  • 259
  • 1
  • 6
0

Try var name = document.getElementById("vname").innerHTML;

Naga Sai A
  • 9,949
  • 1
  • 15
  • 34
0

When you try to access the #vname is not in the DOM yet. You will need to add the script tag after the element or wait for the DOM to be loaded.

When that is said a <p> tag cannot have a value. Use data-value instead:

<p id="vname" data-value="firstname">Loren</p>
<script>
  var vname = document.getElementById("vname");
  var value = vname.getAttribute('data-value');
  console.log(value);
</script>
andlrc
  • 41,466
  • 13
  • 82
  • 108