0

I have the following code:

echo "<div class='hp_container'><div id='hp' val=".$warrior_row[8]."></div></div>";

In this case, val has the value 8.

I want to access this value with JavaScript. I have tried the following method, but it keeps saying that txt is null.

 <script type='text/javascript'>
   var txt = document.getElementById("hp");
   var f = txt.getAttribute('val');
   alert(f);
   </script> 

How can I resolve this?

Edit

I solved the problem by placing the code inside window.onload:

    window.onload = function() {
    var txt = document.getElementById("hp");
    var f = txt.getAttribute('val');
    alert(f);
};
halfer
  • 18,701
  • 13
  • 79
  • 158
Bryan
  • 2,793
  • 7
  • 28
  • 56
  • There is no`val` attribute for the `div` element in HTML. If you want to use custom attributes then use `data-val`. – Quentin Mar 05 '15 at 10:54
  • 1
    So long as your element is in your DOM before you run that JavaScript, that looks like it should work. So: have you tried putting your ` – David says reinstate Monica Mar 05 '15 at 10:55
  • I placed the code inside window.onload. That solved my problem. – Bryan Mar 05 '15 at 10:59

0 Answers0