Search code examples
asp.netcss-selectorscode-behind

possible to reference CSS selector in code-behind ASP.NET


Let's say I have this HTML markup on an aspx page:

      <div id = 'logo-container' class='foo'>
          <img alt='logo' src ="images/foo.png" />
      </div>

Pure html, not runat=server.

Is it possible, in aspx code-behind, to refer to a DOM element using CSS selectors? Could you get a reference to the IMG doing something like this:

 foreach element in GetElement("#logo-container img")
  {
       do something with element, e.g. change a style attribute
  }

Solution

  • No, you cannot, unfortunately. You'd be beter off doing it the intended way. If you need to access the controls in code-behind, just add the runat="server" attribute.

    Why don't you want to run the controls at the server, considering that you need to access them in the code-behind? Are you worried about the auto-generated IDs? If so, you can resolve this by setting ClientIDMode to static.

    If you do run the control at the server, you should be able to find the controls with that class using LINQ like this:

    var ctrls = pnlControls.Controls.OfType<WebControl>().Where(i => i.CssClass == "logo-container");   
    

    Note: You can Replace WebControl with a more specific control if needed.