Javascript DOM How to - Use a string variable in document.getElementById()








Question

We would like to know how to use a string variable in document.getElementById().

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--from w w  w  .  jav  a  2s.  co m-->
    var b = 'name';
    document.getElementById(b).innerHTML = 'none';
}
</script>
</head>
<body>
  <div id="name" style="width: 300px; height: 300px; background: red"></div>
</body>
</html>

The code above is rendered as follows: