2

I have this html structure:

<asp:Panel ID="divOne">
  <div class="divSection1">
  <asp:Panel runat="server" id="specialId" class="ClassOne ClassTwo"
    <asp:Label  id="MyLabel"></asp:Label>
    <div id="myDiv" </div>
  </asp:Panel>
  </div>
</asp:Panel> 

And i am trying to access the "specialId" in jquery like $('#specialId'), $('div.specialId') with no success. Can someone advice?

4
  • check this stackoverflow.com/questions/11389733/… . It does something similar Commented Nov 8, 2013 at 13:23
  • You should provide the actual generated HTML, and not your template code. Commented Nov 8, 2013 at 13:23
  • What does the actual client-side HTML look like? JavaScript doesn't interact with your server-side code. Commented Nov 8, 2013 at 13:24
  • 1
    runat="server" seems to be missing on your tags. If possible, make a selection on the class. Or use the ClientID as stated by @ChiraqVidani Commented Nov 8, 2013 at 13:28

2 Answers 2

6

My similar answer with a little more explanation is here

runat="server" in asp.net adds master and page information to each of its control. So, if you look at the DOM, your control would look something like this master_page_ctrl0_specialId[just an example].

You have a few options.

Option1: Use the client ID - recommended but meh.. not so much. I would try to avoid writing ClientID in javascript as much as possible.

$('#<%= specialId.ClientID %>')

Option2: Using the same ID - not recommended because its really ugly.

$('[id$=specialId]') or $('[id*=specialId]')

The above selectors are any id which ends with specialID and any id which contains specialId respectively.

Option3: Using the class - highly recommended. Because selectors using classes are clean and uncomplicated. Also, I see you've used class, use CssClass instead for .net controls.

$('.ClassOne.ClassTwo')

Option4: Use ClientIDMode="Static", which got introduced in .NET Framework 4.0, on the control so that its ID will stay unchanged. - recommended too.

<asp:Panel runat="server" ClientIDMode="Static" id="specialId" CssClass="ClassOne ClassTwo">
</asp:Panel>
Sign up to request clarification or add additional context in comments.

1 Comment

There is also the overlooked 4th option of using Static ClientIDMode msdn.microsoft.com/en-us/library/…
1

You should use actual generated HTML id using below syntax

That means you need to use client ID which can be accessed via below syntax

$('#<%= specialId.ClientID %>')

1 Comment

This doesn't work if your Javascript file is an external one though. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.