开发者

How do I access the element ID in an asp.net masterpage with JavaScript?

开发者 https://www.devze.com 2023-03-27 19:53 出处:网络
I know there are a few answers to this question. Usually the answers given online involve doing this开发者_开发问答...

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 %>);
0

精彩评论

暂无评论...
验证码 换一张
取 消