简体   繁体   中英

Find element by attribute in aspx

<div id="foo" runat="server" data-id="bar"></div>

In the code behind, this div can be accessed either directly on the id or using FindControl() .

But is there any way to search for elements on an aspx based on another attribute than id? Like data-id="bar" above for example.

This extension method (which uses recursion) might be helpful:

public static IEnumerable<Control>
    FindControlByAttribute(this Control control, string key)
{
    var current = control as System.Web.UI.HtmlControls.HtmlControl;
    if (current != null)
    {
        var k = current.Attributes[key];
        if (k != null)
            yield return current;
    }
    if (control.HasControls())
    {
        foreach (Control c in control.Controls)
        {
            foreach (Control item in c.FindControlByAttribute(key, value))
            {
                yield return item;
            }
        }
    }
}

Sample usage:

protected void Page_Load(object sender, EventArgs e)
{
    var controls = this
        .FindControlByAttribute("data-id")
        .ToList();
}

If you also want to filter by the value:

public static IEnumerable<Control>
    FindControlByAttribute(this Control control, string key, string value)
{
    var current = control as System.Web.UI.HtmlControls.HtmlControl;
    if (current != null)
    {
        var k = current.Attributes[key];
        if (k != null && k == value)
            yield return current;
    }
    if (control.HasControls())
    {
        foreach (Control c in control.Controls)
        {
            foreach (Control item in c.FindControlByAttribute(key, value))
            {
                yield return item;
            }
        }
    }
}

you would need to see what the attributes are for that control you iterate through in the FindControl or if you are accessing the element directly like so:

this.foo

then you can use the Attributes collection to see what the specified attribute value is. http://msdn.microsoft.com/en-us/library/kkeesb2c(v=vs.100).aspx

but to answer your question - no, there is not unless you iterate a container/parent control using FindControl()

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