Selecting elements in a usercontrol using JavaScript
I have a web form that contains a usercontrol and I would like to be able to access the html elements within the usercontrol from the form page using javascript.
I tried the following:
document.ge开发者_如何学GotElementById('<%= usercontrol.clientid %>')
but this returned null
.
I had a look around with firebug and found that the tags in the usercontrol render with clientids like usercontrolid_myelement. I'm guessing that something like this might work:
document.getElementById('<%= usercontrol.clientid %>'+'_myelement')
Is there a better/nicer way of doing this?
I have seen through your question with my psychic powers!
Your problem is that your serverscript in your main page can't access the ASP.net elements of your usercontrol.
The solution is to expose the elements, or just the ClientIDs of the elements you need, through properties in the usercontrol. Then you can use the ClientIDs in Javascript like you want to.
Your problem is likely due to the javascript running before the html is fully loaded.
following results in null
<head>
<script type="text/javascript">
alert(document.getElementById('main'));
</script>
</head>
<body>
<div id="main">
</div>
</body>
this is better and returns the object
<head>
function foo(){alert(document.getElementById('main'));}
</head>
<body onload="foo();">
<div id="main">
</div>
</body>
If your using .net 4 then you can stop the generated ids from being in that weird format. Just add this property the asp.net ClientIDMode="Static" e.g.
That should make it easier to access in the dom from javascript.
精彩评论