简体   繁体   中英

Access tag “option” in HtmlElement

need to change this:

<select name="asdf">
    <option selected>a</option>
    <option>b</option>
    <option>c</option>
</select>

I got the HtmlElement but cant change it via htmlEle.SetAttribute("value", "c");

I want to change the selected option from a to c .

Once you have the element, you can loop through the children and update the selected attribute:

var ele = webBrowser1.Document.GetElementById("asdf");

if (ele != null)
{
    foreach (HtmlElement child in ele.Children)
    {
        child.SetAttribute("selected", "false");
        if (child.InnerText == "c")
            child.SetAttribute("selected", "true");
    }
}

Assuming: htmlEle is the option Element,

C#: Please try:

  htmlEle.textContent = "a1";

to make the option appearing gas selected,

 htmlEle.setAttribute("selected", "true");

HTML/JavaScript:

You mean you want to change the display value of first option from a to c , then try below:

      htmlEle.innerHTML = "c";

to make the option appearing gas selected,

htmlEle.setAttribute("selected", "selected");

If I have an ID assigned to selectbox as:

      <select name="asdf" id="selectBox">
         <option selected>a</option>
         <option>b</option>
         <option>c</option>
       </select>

Then

  var selectElem = document.getElementById("selectBox");
  selectElem.childNodes[1].innerHTML = "a1";

changes value of first option as a1 .

This is done easily with

htmlEle.value = "c";

Live DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM