Web Owl
Web Owl

Reputation: 569

append value to element with javascript (not jquery)

<script>
var cool = "cool";
var pass = document.getElementById('name');
pass.innerHTML = cool;
</script>
<small id="name"></small>

To be honest I am just not searching correctly; this seems very basic. I have been using jquery for everything, but never actually used much JS by itself, so I am wondering how one would append a value to an element using just JS.

Upvotes: 2

Views: 3181

Answers (3)

woofmeow
woofmeow

Reputation: 2408

Basically you executing the javascript before creating the html

<small id="name"></small>

so the javascript does not work on the non-existent html .

Upvotes: 0

Netwidz
Netwidz

Reputation: 179

Your code should work... you have to define the JS after

<small id="name"></small>

If not there might be a problem which try to search DOM element before it loads

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

Your code should work, but you need to add it after the element is defined, otherwise document.getElementById('name') will return null as name element doesn't exist yet.

<small id="name"></small>
<script>
var cool = "cool";
var pass = document.getElementById('name');
pass.innerHTML = cool;
</script>

Upvotes: 3

Related Questions