Vivian River
Vivian River

Reputation: 32390

How do I access a DIV from javascript, if ASP.NET mangles its ID?

I have a web page that contains a "div" element. On the page, there is javascript to reference the div: document.getElementById('divId'). This was working fine until another developer redesigned the page to use an ASP master page.

Now, document.getElementById('divId') returns null. It appears that ASP.net prepends some characters to the names of elements within contents forms when you use a master page. How can I know what the id of the div is when the page loads?

Update Allow me to give a specific example to clarify the question: My page had a div with ID divNotice. After changing my page to use a master page, I see when I print the source to the page that renders that the div ID is ctl00_ContentPlaceHolder1_divNotice. My question is, how am I supposed to know what the div ID is going to be when the framework is done with it?

Upvotes: 3

Views: 5210

Answers (4)

Gerardo Jaramillo
Gerardo Jaramillo

Reputation: 485

maybe you can use a descendent selector un css

<div id="wrapperControler">
    <controler id="controler"></controler>
</div>

wrapperControler controler{

 dosomething;

}

Upvotes: 0

meo
meo

Reputation: 31249

you can check i the element exists by checking if it returns not null

if (document.getElementById('divId') != null) { /* do your stuff*/ }

in other words:

if (document.getElementById('divId')) { /* do your stuff*/ }

now you have edited you orginal question i got it.. i would do something like this:

var arrDivs = document.getElementsByTagName('div'),
    strDivName = "divId";

for (i=0;i<=arrDivs.length;i++){
    if( arrDivs[i].id.indexOf(strDivName) != -1) {
        alert("this is it")
    }
}

you can see a demo here: http://jsfiddle.net/pnHSw/2/

i think you could do it better with a regex.

But this is a pure JS way i don't know ASP.net

edit: i think Aristos solution is much cleaner :P

Upvotes: 1

Aristos
Aristos

Reputation: 66641

I think that this is what you looking for.

document.getElementById('<%=divNotice.ClientID%>')

to get the ID of your element as appears on the html page use .ClientID

Hope this help.

Upvotes: 10

seren23
seren23

Reputation: 596

Dynamically create the javascript using Control.ClientID to determine the calculated ID of div.

document.getElementById('<%= DivControl.ClientID %>')

Or search for the element on the client side using the base ID as a search pattern. See here: A generic way to find ASP.NET ClientIDs with jQuery

I prefer the server side calculation, but if you don't do it often and/or your current design prohibits it, the client side way is a reasonable workaround.

Upvotes: 2

Related Questions