I’m trying to understand HTML elements that are dynamically created with JavaScript. Specifically can someone explain why if I create a button in HTML with no value attribute it will appear with no text. I can then add a value to it and the text will appear in the button, and I can also alert the value like so:
var Button1 = document.getElementById("Button1");
Button1.value = "test";
alert(Button1.value);
BUT, if I generate the button dynamically and then add the value it does NOT appear on the button, although I can still alert it.
var Button1 = document.createElement("button");
var Div1 = document.getElementById("Div1");
Button1.value = "test";
Div1.appendChild(Button1);
alert(Button1.value);
In the second example, the text of the button doens’t change, but the value still alerts. I KNOW that I can use createTextNode and append it to the button, but I’m trying to understand the difference between controls generated dynamically through JavaScript and those that are created in HTML.
Thank you for reading my question.
In your second example you’re creating a new element and assigning a value to it, but you haven’t added it to the DOM — it exists purely in JavaScript which is why the alert works. In order to see the button on the page, you would need to append it to the document, typically with appendChild().
You said, “BUT, if I generate the button dynamically and then add the value it does NOT appear on the button, although I can still alert it.” and “the text of the button doens’t change, but the value still alerts” which confuses me a little since it seems as if you might have a button already on the page which you expect the second example’s code to change.
Your first example is a textbook example of how to get an element that exists in the DOM already, assign (or change) its value, and then alert it.
Update: To answer your revised question, your code is changing the button’s value, but if you expect to see the text of the button on the page change, you need to alter its innerHTML value, like with
Button1.innerHTML = "test";. Button elements aren’t like input buttons where the value is shown as the text of the button. The text of a button element comes from the text between the opening<button>and closing</button>tags.Example:
<button value="test">test</button>