Чтобы изменить выбранную опцию HTML-элемента с помощью JavaScript, вы можете использовать различные методы. Вот несколько подходов:
-
Использование свойства
selectedIndex:var selectElement = document.getElementById("mySelect"); selectElement.selectedIndex = 2; // Change to the desired index -
Использование свойства
valueэлемента:var selectElement = document.getElementById("mySelect"); selectElement.value = "optionValue"; // Change to the desired value -
Использование метода
querySelector:var selectElement = document.querySelector("#mySelect option[value='optionValue']"); selectElement.selected = true; // Set the selected attribute to true -
Использование метода
querySelectorAllс циклом:var options = document.querySelectorAll("#mySelect option"); for (var i = 0; i < options.length; i++) { if (options[i].value === "optionValue") { options[i].selected = true; // Set the selected attribute to true break; } }