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?
STEP 1 − Create a select tag with multiple options and assign an id to the select tag. STEP 2 − Also, create an empty DOM with an id to display the output. STEP 3 − Let there be a button element for the user to click and see the option selected. STEP 4 − Let the user select an option from the dropdown list.
Example Explained Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.
To get an XPATH of an element right-click the Dropdown menu and select 'Inspect element with Firebug'. Then corresponding code would be highlighted in the firebug, right-click on it and select copy XPath. By this method we can copy the XPATH and paste it into the Selenium IDE tool's Target section.
This will work (pure JS, appending to a div of id myDiv
):
Demo: http://jsfiddle.net/4pwvg/
var myParent = document.body; //Create array of options to be added var array = ["Volvo","Saab","Mercades","Audi"]; //Create and append select list var selectList = document.createElement("select"); selectList.id = "mySelect"; myParent.appendChild(selectList); //Create and append the options for (var i = 0; i < array.length; i++) { var option = document.createElement("option"); option.value = array[i]; option.text = array[i]; selectList.appendChild(option); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With