Javascript – use querySelector to set dom element html

Javascript querySelector can be used to select and set html of a dom element using css selectors. This can be done with jQuery also. But at times you don’t have access to jQuery and want to do it in plain Javascript. Here is code snippet for it.

<div id=hello>
</div>
<script type="text/javascript">
window.addEventListener('load', update_hello);
function update_hello() {
  document.querySelector("#hello").innerHTML = '<span style="color:blue;">Hello World</span>';
}
</script>
refresh

Note that querySelector and addEventListener work in most modern browsers including IE9 and above.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments