C# get element by name

落花浮王杯 提交于 2019-11-28 08:18:39

问题


Soo ive figured out how to get element by id, but i dont know how i can get element by name Here is my code:

private void SendData()
{
    webBrowser1.Document.GetElementById("textfield1").SetAttribute("value", textBox1.Text);
    webBrowser1.Document.GetElementById("textfield2").SetAttribute("value", textBox1.Text);
}

The problem is in my html code only textfield1 is a id but textfield2 is name soo i want to figure out how to get textfield2

Here is my html code:

<html>
    <input type="text" id="textfield1" value="TEXT1"><br>
    <input type="text" name="textfield2" value="TEXT2"><br>
    <input type="submit" value="Submit">
</html>

回答1:


You can get an HtmlElementCollection - for example, using GetElementsByTagName method. Then, HtmlElementCollection has GetElementsByName method:

webBrowser1.Document
    .GetElementsByTagName("input")
    .GetElementsByName("textfield2")[0]
        .SetAttribute("value", textBox1.Text);



回答2:


You can use HtmlElementCollection.GetElementsByName to take the value of the elements

webBrowser1.Document.GetElementsByName("textfield2").SetAttribute("value", textBox1.Text);

EDIT

foreach (HtmlElement he in webBrowser1.Document.All.GetElementsByName("textfield2"))
{
    he.SetAttribute("value", textBox1.Text);
}



回答3:


You can't access the elements directly by name, but you could access it by finding the input tags first, and indexing into the result to find the tags by name.

webBrowser1.Document.GetElementsByTagName("input")["textfield2"]

or

webBrowser1.Document
    .GetElementsByTagName("input")
    .GetElementsByName("textfield2")[0]


来源:https://stackoverflow.com/questions/32904235/c-sharp-get-element-by-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!