How do I make this getElementsbyName work for IE (and FF)?

This is the JavaScript that is errored on in IE but works in FF (error – “document.getelementsbyname(…).0.innerhtml is null or not an object”:

var oldVal = parseInt(document.getElementsByName("outSL")[0].innerHTML); //val from DB

This is the asp.net code where I want to grab the inner html that will be filled in by the database:

<asp:Label ID="LabelSL" runat="server" Text="" name="outSL" style="visibility:hidden;"></asp:Label>

The id is dynamic, when it is rendered it looks like this, where it is the 43 I am after:

<span id="ctl00_cpMainContent_LabelSL" name="outSL" style="visibility:hidden;">43</span>

So…how can I get that 43 in IE and FF with the same function?

Thank You!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

GetElementByName functions differently across different browsers. I suggest you access your elements using jQuery.

Method 2

If you have .NET 4.0 then you can write clean id’s and then just use getElementById, since as Carnotaurus state’s, getElementByName functions different across browsers.

http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx

If you’re stuck on .NET 2.0/3.5, then you can use jQuery to access elements by either Id, or Name, or many other selectors.

http://api.jquery.com/category/selectors/

Also I wrote a library to output a json array of ID’s for .NET 2.0/3.5.

http://awesomeclientid.codeplex.com/

http://www.philliphaydon.com/2010/12/i-love-clean-client-ids-especially-with-net-2-0/

This gets around the INamingContainer slapped on all the controls runat server, it outputs an array like:

<script type=”text/javascript”>
//<![CDATA[
var controls = {
"txtUserName": "ctl00_ContentPlaceHolder1_txtUserName",
"txtEmail": "ctl00_ContentPlaceHolder1_txtEmail",
"btnSubmit": "ctl00_ContentPlaceHolder1_btnSubmit"
};
//]]>
</script>

Then you can access the elements by ID like so:

var element = document.getElementById(controls.btnSubmit);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x