I have an ASP.NET site that I am trying to access div elements by their ID from the C# code behind file. Essentially I want to see if a div element exists, and if so, alter its
I cannot seem to be able to reproduce your problem, any chance your DIV's are within a template control such as UpdatePanel, Repeater, or Grid?
If your page is using a MasterPage, the div control will not be in the main collection of controls. That collection only contains the Content controls pointing to the ContentPlaceholder of your MasterPage.
There are three options:
FindControl
on the Content control: contentControl.FindControl("button1");
FindControl
until you find the control you needbutton1.Attributes["class"] = "classNameHere";
I have created a MasterPage, added a Content Page to it, and added <div id="button1" runat="server">Some text</div>
to the Content Page.
In the codebehind of my Content Page, I added this code:
protected void Page_Load(object sender, EventArgs e)
{
var control = FindHtmlControlByIdInControl(this, "button1");
if (control != null)
{
control.Attributes["class"] = "someCssClass";
}
}
private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) && childControl is HtmlControl)
{
return (HtmlControl)childControl;
}
if (childControl.HasControls())
{
HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
if (result != null) return result;
}
}
return null;
}
This works for me.
If you add runat=server
please add it at last of the div:
This will work
<div id="divBtn" class="mybuttonCass" runat="server">
However, this will not
<div runat="server" id="divBtn" class="mybuttonCass">
By doing that, you can modify any property from codebehind as:
divBtn.Style["display"] = "none";
This works even with masterpages. The div is not included in a masterpage.
You need to add a runat=server attribute to any control that you want to access in code behind. See this article for more help.
Accessing <div> from both javascript and code-behind