getElementsByClassName not working on firefox - javascript

I was trying to print a anual report but i need to change 2 texts around the page, one of them has only a class attribute. Im new at js so i made this.
<div id="formBusqPresElec:dtResBSPE_paginator_bottom" class="ui-paginator ui-paginator-bottom ui-widget-header">
<span class="ui-paginator-current">Mostrando 1-20 de 1626 registros</span>
</div>
And the other has an id.
<div id="fBusqSPE">Mostrando 20 de 1626 registros</div>
I made it work on Chrome
function imprimir() {
var oldText = document.getElementById('fBusqSPE').innerText;
document.getElementById('fBusqSPE').innerText = document.getElementsByClassName('ui-paginator-current')[0].innerText;
window.print();
document.getElementById('fBusqSPE').innerText = oldText;
}
But in firefox throws
[10:48:48.330] TypeError: document.getElementsByClassName(...)[0] is
undefined
Edit: So let me explain more.
Actually im working inside 2 iframes, which the first one is for the menu, and the other one is for more options. Then the central iframe is used to show the actual report.
Maybe I must define which iframe I want to retrieve those elements.

There are 2 problems here. The first causes your error of document.getElementsByClassName(...)[0] is undefined and once overcome, the second is that Firefox does not support innerText
The only way to generate the specified error in Firefox is for no elements with the specified class being present on the page. This is demonstrated by the following code
<div class="a-test"></div>
// on page load
document.getElementsByClassName("b-test")[0].innerHTML="Test";
JSFiddle:http://jsfiddle.net/UL2Xs/
If you watch the console when running the above fiddle, you'll see the same error as you get.
Is it possible that your javascript is running before the page has finished loading?
The second, and more minor issue is that FireFox does not support innerText. You should use .textContent or possibly .innerHTML.

You probably should use:
iframe.contentDocument.getElementsByClassName(...)
(see: contentDocument for an iframe)

Basically .innerText will not work in FF. FF uses textContent property.
var text = element.textContent;
element.textContent = "this is some sample text";

Related

IE9 crashes when hiding DIVs

NOTE:
Sorry, I don't yet have code to support this article (sensitive production code only). I will attempt to provide a concise working sample if time permits later. I wanted to publish this in the hopes it can offer hints to others in tracking down similar issues.
Using
Internet Explorer 9.
jQuery 1.9.2 and 2.0.0.
HTML5 doctype
Scenario
I have a page split into logical "screens".
Each screen is a DIV identified by class names (e.g. "formScreen", "errorScreen", "confirmationScreen").
".formScreen"'s contain form (data input) fields, and the whole page has single submit button which generates a JSON package from the form data and performs an AJAX post-back.
I fill in the form "in a certain way" (the order in which I fill in the form seems to make a difference), then submit.
After a response is received by the submit, the code updates the display.
The Problem
Hiding all "formScreen" DIVs after submitting causes IE9 to completely crash.
Originally I define a formScreens variable:
var formScreens = $(".formScreens");
then later call:
$(formScreens).hide();
which causes IE to crash.
I also tried the following, and both options also cause the crash:
var copyOfFormScreens = $("div.formScreen");
$(copyOfFormScreens).each(function ()
{
$(this).hide(); // Option 2: This fails too.
$(this).css("display", "none"); // Option 3: This fails too.
});
IE crash error
The following was returned by IE when crashing:
Problem signature:
Problem Event Name: APPCRASH
Application Name: IEXPLORE.EXE
Application Version: 9.0.8112.16496
Application Timestamp: 51a55c6d
Fault Module Name: MSHTML.dll
Fault Module Version: 9.0.8112.16496
Fault Module Timestamp: 51a55ff0
Exception Code: c00000fd
Exception Offset: 0032ef01
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 3081
Additional Information 1: 39a4
Additional Information 2: 39a4d7f18c1c7c725934453009d2f1b9
Additional Information 3: ddcf
Additional Information 4: ddcfafd1b35f05f847ac8d3e7a7bcf12
And the following when debugging in Visual Studio:
Unhandled exception at 0x6302EF01 (mshtml.dll) in iexplore.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x02432F68).
Unhandled exception at 0x630A172B (mshtml.dll) in iexplore.exe: 0xC0000005: Access violation writing location 0x02430FFC. // This error continued to show when pressing the debug "continue".
Workaround/Solution
There is a very simple workaround I discovered.
Before hiding the desired elements I set the focus to an element "outside" the DIVs that are hidden (i.e. an element that is still visible after the screen DIVs are hidden).
In my case, I set the focus to the first container DIV in the page, which turns out to be an ancestor for DIVs being hidden.
An idea of how the DIV layout looks:
<div class="mainContent">
<div class="fromScreen">
</div>
<div class="fromScreen">
</div>
<div class="fromScreen">
</div>
</div>
So the code I now call is:
$(".mainContent").trigger("focus"); // Call this before the hide.
formScreens.hide(); // Crashes on submit if focus is not set to higher element first.
Key takeaway
If hiding a DIV with elements that have focus prior to hiding causes issues, move the focus to an element outside the DIV being hidden.
(My workaround was inspired by the first response at http://www.3dvia.com/forums/topic/urgent-crash-in-internet-explorer-when-trying-to-hide-the-experience)
I have a workaround as well. If you set explicitly the "visibile" CSS property to "Visible" value than hide the outer div (set Visible to Collapse), it works. Without this step, IE crashes.
However this solution does not work in other browsers, because the internal content still remains visible. So, I just simply detect the browser type than in IE I set the internal DIVs visibility to "Visible", in other browsers to "Inherit".
The behavior of the IE is strange, because it will hide the entire content as I originally expected, however the logical working is to keep internal content are visible as in other browser.
The crash is a bug in IE, it still exists in IE11 too.
Example for IE:
<div id="outerDiv">
<div style="visibility:visible">To hide</div>
</div>
Example for other browsers:
<div id="outerDiv">
<div style="visibility:inherit">To hide</div>
</div>
Now set "outerDiv" Visibility to Collapse.

Javascript auto-calcs won't run in FF, works fine in IE and Chrome

I have the following asp.net textbox defined in markup:
<div class="OptionSelect2">
<asp:TextBox ID="txtCalculateWeightRollSize" CssClass="_100" runat="server"></asp:TextBox>
</div>
In the code-behind, on Page_Load, I am binding the onblur event:
txtCalculateWeightRollSize.Attributes.Add("onblur", "Javascript:RollBWghtPCutoffNWebsCalcs();")
The Javascript (reformatted to more easily to fit into a question format), is as such:
function RollBWghtPCutoffNWebsCalcs() { ZeroPctLbs(); }
function ZeroPctLbs() {
//Get the values
var rollSize = document.getElementById("<% =txtCalculateWeightRollSize.ClientID %>").value.replace("$", "").replace("%", "");
//Get other controls' values
//Make them numbers, if necessary
rollSize = +rollSize;
//convert other controls
//Calculate and assign the result
var result = //math;
document.getElementById("<% =lblCalculateWeightZeroPercentLbsValue.ClientID %>").innerText = result;
}
This works without a problem in both IE and Chrome. However, in Firefox, it fails. In firebug (which I have not used until today), it appears that the onblur event fires, but stepping into the code, when it should be calling RollBWghtPCutoffNWebsCalcs(), it passes over it as though the calling doesn't exist. If I place a breakpoint directly inside any of the Javascript functions, it is never triggered.
The textbox appears to be rendered correctly in HTML:
<input name="ctl00$MainContent$txtCalculateWeightRollSize" type="text" id="MainContent_txtCalculateWeightRollSize" class="_100" onblur="Javascript:RollBWghtPCutoffNWebsCalcs();" />
Here is a JSFiddle that I believe shows the issue. The onblur doesn't work in any browser in the fiddle, but that would be consistent with my experience with Firefox issues in the past. It does work in Chrome and IE when rendered directly, and JSHint indicates that the Javascript is valid.
I suspect something I'm doing isn't completely standard, as Firefox (by my understanding) is pretty much a standards-based web experience. WHY WON'T IT RUN? Please.
Sometimes it's the simple things...
.innerText isn't supported by FireFox. Use innerHTML instead.
Once I stopped using Firebug and switched to FF's built-in debugger, I was able to actually trace my code - I guess I just don't know how to use Firebug. The odd thing that threw me off was that FF would get the values FROM the labels using innerText, and would write them in such a way that subsequent function calls could read the written values, but it would not render the innerText.
tldr;
Use innerHTML to work with label text in Javascript.

javascript: get contents of textarea, textContent vs. innerHTML vs. innerText

I am having trouble getting the contents of a textarea with js. I feel like I've done this many times before without problems but something is throwing it off or I have a mental block.
html
<textarea id="productdescript">test copy..asdfd</textarea><button value="Enter" onclick="addProduct()">
js
function addProduct() {
var descript = document.getElementById('productdescript').textContent;
alert(descript);
}
Firefox is the only browser I have currently.
When I use textContent, the alert box appears but it is blank.
When I use value, the alert box appears and says "Undefined"
When I use innerHTML, all the HTML appears including the tags.
Also, I understand that textContent only runs in FF and for cross browser compatibility you need to do something like innerText and textContent but textContent is not working in FF. There is no jquery on this app
What is the correct cross browser way to get contents of textarea! Thanks for any suggestions.
For textarea, you could only use .value in your scenario (I tested your given code and it works fine).
.
Also,
1) keep in mind that you call this function addProduct() ONLY after your element is mentioned in the code, otherwise it will be undefined.
2) there must not be another element with id as productdescript
3) there must not be a JS variable called productdescript
This are your code?
you write document.getElementByID.... and the "D" should be written lowercase "d"
document.getElementById('productdescript').textContent;

Inserting <style> tags from a string in Internet Explorer

I'm loading a string via AJAX that reads like
<style>[some definitions]</style>
<h1>Lots of Markup</h1>
<p>follows here</p>
Using Webkit/Gecko everything works as expected — the markup is inserted, styles are applied. In IE (8) though the style-definitions are ignored. Actually, if you use the developer tools they are gone.
You can see in this JS-Fiddle that it doesn't work: http://jsfiddle.net/J4Yzr/
Also, I've seen that trick that you create a temporary DOM-Object, set it's innerHTML to your markup and extract your markup as DOM-Objects from your temporary element. That doesn't work with style tags (if I did it right, I'm using prototypeJS):
var text = '<style>h1{color:red;}</style> style added',
el = new Element('div').update(text);
console.log(el.firstChild);
//is a HTMLStyleElement in Webkit but a [object Text] in IE
Does anyone have a suggestion how to properly apply the <style> in IE if you get it from such a string?
I had the same problem, so I tried your solution, but guess what? When I stripped the out after rendering markup retrieved via Ajax, the tags disappeared from the DOM! Back to square one.
So my solution is to prepend this instead:
<hr style='display:none'/>
Which did the trick nicely. Thank you so much for solving this issue.
Ok, it's crazy. Add a <br/>-Tag in front of your string and it works in Internet Explorer.
<br/><style>[some definitions]</style><h1>Lots of Markup</h1>
You don't even need to create that temporary DOM-Object to insert code into. Just append it in your site.
What I'm doing now it insert the code with a <br/>-Tag and remove the <br/> afterwards. It's messy but it works.

Changing content using innerHTML with a non-standard element in Internet Explorer

I have the non-standard element
<testele></testele>
In every browser except IE, this bit of JavaScript will successfully change the content of the above element
document.getElementsByTagName("testele")[0].innerHTML = 'hi';
However, if I change the <testele> to just a <span> (in the HTML and the JavaScript), it now successfully changes the content of the element in every browser, including IE.
Is there any fix? I have searched around and tried a bunch to no avail.
Use document.createElement("testele") before it is rendered. This script must be included before the document encouters a <testele>:
http://jsfiddle.net/gilly3/LjwbA/
document.createElement("testele");
window.onload = function() {
document.getElementsByTagName("testele")[0].innerHTML = 'hi';
};
If you try to do document.createElement("testele") after a <testele> has been parsed by the browser, it's too late.
Take a look at innerShiv, a Javascript plugin which aims to solve this.

Categories