How do I access the element ID in an asp.net masterpage with JavaScript?
I know there are a few answers to this question.
Usually the answers given online involve doing this开发者_开发问答...
document.getElementById (<%=myElementID.ClientID %>);
rather than this...
document.getElementById("myElementID");
However, even when I do it the first way, my JavaScript code still cannot find the element. It tells me the element is undefined.
So...just for testing...I tried to strip out all my JavaScript code and access the element with an alert box like this...
<script type="text/javascript">
alert(document.getElementById('<%=searchHyperLink.ClientID %>').value);
</script>
It still tells me its undefined.
But its not freaking undefined! When I view the page source, the id rendered by <%=searchHyperLink.ClientID %> exactly matches the id of the control I want to find.
Any suggestions?
To expand on Evan's comment, if you're doing the document.getElementById
in a script tag that's before the element in the ordering of the document, it will return undefined
. Try this instead:
<html>
<head>
<script>
function postLoadFn() {
alert(document.getElementById('<%=searchHyperLink.ClientID %>').innerHTML);
}
</script>
</head>
<body onload="postLoadFn();">
<!-- Your markup here -->
</body>
</html>
I've used parent
to access a higher level in my project asp.net masterpage(home.master).
Instead of:
document.getElementById (<%=myElementID.ClientID %>);
Use:
parent.window.document.getElementById (<%=myElementID.ClientID %>);
精彩评论