I want to create a function in order to programmatically add some elements on a page.
Lets say I want to add a drop-down list with four options:
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
How can I do that?
This will work (pure JS, appending to a div of id
myDiv
):Demo: http://jsfiddle.net/4pwvg/
it's very simple yet tricky but here is what you wanted, hope it's helpful : this function generates a select list from 1990 to 2018 i think this example can help ya, if you want to add any other value just change value of x and y ;)
Here's an ES6 version of the answer provided by 7stud.
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
Pure Javascript Create Element Solution
lets see how we make this
here's how it works
this is the params
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
JSFiddle Demo
This can be highly customized to suit your project!
This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.