The DOM Datalist Object is used to represent the HTML <Datalist> element. The Datalist element is accessed by getElementById().
Properties: It has an 'Option' attribute which is used to return the collection of all options values in a datalist.
Syntax:
document.getElementById("gfg");
Where "gfg" is the ID assigned to the "Datalist" Tag.
Collections:
options: It is used to return the number of options in an <datalist> element.
Example 1: In this example, we will use DOM Datalist Object
HTML
<!DOCTYPE html>
<html>
<body>
<h1 style="color:green;font-size:39px;">
GeeksForGeeks
</h1>
<h2>DOM Datalist object</h2>
<form>
<label>Your Cars Name: </label>
<input list="gfg">
<datalist id="gfg">
<option value="BMW" >
<option value="Bentley" >
<option value="Mercedes" >
<option value="Audi" >
<option value="Volkswagen" >
</datalist>
</form>
<br>
<button onclick="myGeeks()">Submit</button>
<p id="sudo"></p>
<script>
function myGeeks() {
let g =
document.getElementById("gfg").options.length;
document.getElementById("sudo").innerHTML =
"There are " + g + " options in the list.";
}
</script>
</body>
</html>
Output:
Example 2: In this example, we will HTML DOM Datalist Object.
HTML
<!DOCTYPE html>
<html>
<body>
<h1 style="color:green;font-size:39px;">
GeeksForGeeks
</h1>
<h2>DOM Datalist object</h2>
<form id="GFG">
<b><label>Your cars name:</label></b>
</form>
<br>
<button onclick="myGeeks()">Submit</button>
<script>
function myGeeks() {
let g = document.createElement("INPUT");
g.setAttribute("list", "cars");
document.getElementById("GFG").appendChild(g);
let f = document.createElement("DATALIST");
f.setAttribute("id", "cars");
document.getElementById("GFG").appendChild(f);
let w = document.createElement("OPTION");
w.setAttribute("value", "BMW");
document.getElementById("cars").appendChild(w);
let x = document.createElement("OPTION");
x.setAttribute("value", "Mercedes");
document.getElementById("cars").appendChild(x);
}
</script>
</body>
</html>
Output:
Supported Browsers: The browser supported by DOM Datalist Object are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Opera
- Safari
Explore
HTML Basics
Structure & Elements
Lists
Visuals & Media
Layouts & Designs
Projects & Advanced Topics
Tutorial References