Home > Web Front-end > JS Tutorial > body text

Dynamically create option in select element

DDD
Release: 2024-10-20 22:35:30
Original
958 people have browsed it

Dynamically create option in select element

There are two ways to create an option dynamically :

1) Using the Option constructor and add() method

2) Using the DOM methods

1) Using the Option constructor and add() method :

let newOption = new Option('Option Text','Option Value');
const select = document.querySelector('select'); 
select.add(newOption,undefined);
Copy after login

2) Using the DOM methods :

// create option using DOM
const newOption = document.createElement('option');
const optionText = document.createTextNode('Option Text');
// set option text
newOption.appendChild(optionText);
// and option value
newOption.setAttribute('value','Option Value');

const select = document.querySelector('select'); 
select.appendChild(newOption);
Copy after login

The above is the detailed content of Dynamically create option in select element. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!