Debugging IE8 Javascript Replace innerHTML Runtime Error - javascript

function DeleteData(ID)
{
var ctrlId=ID.id;
var divcontents=document.getElementById(ctrlId).innerHTML;
var tabid=ctrlId.replace(/div/,'tab');
var tabcontents=document.getElementById(tabid).innerHTML;
alert(document.getElementById(tabid).innerHTML);
document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>";
document.getElementById(ctrlId).innerHTML='';
}
I am trying to replace the Table with empty table but
document.getElementById(tabid).innerHTML="<TBody><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></TBody>";
this line is causing Unknown Runtime Error

You can't set value to a table's innerHTML, you should access to child cells or rows and change them like that :
document.getElementById(tabid).rows[0].cells.innerHTML = 'blah blah';
For more info/example : Table, TableHeader, TableRow, TableData Objects

In IE8, you cannot change the innerHTML of an object when the code that attempts that is fired from within the object.
For example:
<span id='n1'>
<input type=button value='test' onclick='DoSomething(this);'>
</span>
with the following code tucked in some remote corner of your document:
<script type='text/javascript'>
function DoSomething(element)
{
document.getElementById("n1").innerHTML = "This is a test"
}
</script>
This will fail with the error unknown runtime error. I believe it has to do with the fact that you're trying to replace the HTML code which fired the current line of execution. The onclick event is part of the code being replaced by the DoSomething function. IE8 doesn't like that.
I resolved my issue by setting a timer event for 250 milliseconds, such that the function called at the end of the 250 milliseconds replaces the span's innerHTML.

I find out that in IE8 some elements are in readonly: COL, COLGROUP, FRAMESET, HEAD, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR.
Therefore if you try to set innerHTML for these elements IE8 notify alter with Unknown Runtime Error.
More details here: http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx.
The simplest way is to convert read-only elements to div element.

I had the same issue but my error was because I was inserting a p tag directly underneath a p element as in:
document.getElementById('p-element').innerHTML = '<p>some description</p>';
I don't really see how this is HTML format error; seems more like another IE8 bug.

Great, I had the same situation with setting the innerHTML. When I read this I realised that one of the elements was a TR and one was a TD and the TD was working.
Changing the code so that they're both TDs fixes it, which means that it is a rather non-obvious problem caused by the structure of tables.
Presumably it throws the DOM awry when I start changing table rows since it can't store the table as an array any more.
I'm sure IE could give a more informative error message since it can't be that uncommon for the DOM to change on the fly and it seems strange that this would only throw an error for tables.

Ohh yes - remember that the HTML structure has to be valid.
I tried loading an entire page into a <p> tag - it failed (obviously), changing it to a <div> tag solved my problem!
So remember the HTML structure!

why it happend in IE...
case scenario:
Javascript unknown runtime error in IE while accessing Div inside Div to add ajax contents.
solution:
dont ever place nested divs in between the form tags to play with there contents .. :)

When using YUI try to use
Y.one('#'+data.id).setContent(html);
instead of:
Y.one('#'+data.id).set('innerHTML' , html);

If you need to set innerHTML to "" (empty string) then you can use removeChild instead

This is not a Big issue, since i faced same problem few days ago and the reason this error
occurs in ie is that - There exists an error in our html format or you are using an element other than <td> to replace innerHTML ie use only, dont use tables,divs to replace innerHTML.
SwapnilK

Related

element.innerHTML not giving full data

I'm trying to get the innerHTML of an YUI table element. Whenever I try to do so the innerHTML or .html() (jQuery) doesn't give me full html but only a part of it. I'm confused why is it happening. I don't think there is some kind of upper bound to the size of html() we can retrieve. Here is my code..
alert(document.getElementById("table").innerHTML);
console.log($("#table").html());
$.post("MainPageHTML",
{
"data" : $("#table").html()
},function(result){
TCProJSM.newsClicked = false;
location.href = result;
},
"text"
);
Please help and thanks in adance.
Basically I want to save the state of my current page(means all the selections, maps etc on it) while I'm migrating away from it to another page, so when I comeback to this page I just have to repaint the page with my saved stuff. For that I'm doing .html() for the elements required and posting the data to server to be saved. But as I said above I'm getting incomplete data (only few lines from the beginning) for every element I want to save it's state for.
Is there any thing else I can try apart from HTML to get the data which can be repainted when I visit the page again ??
try to use .html() in jQuery.It will give the whole html.
innerHTML can't be applied for several DOM elements, such as table, tr or select, instead of it should be used childNodes or something similar.
In your situation it will be better to create some json file based on #table data and post exactly it.

Firefox add <a xmlns="http://www.w3.org/1999/xhtml">

EDIT: This isn't happening because of the ajax call. I changed it to use a value from a TinyMCE component for fun and I get the same thing.
content = tinyMCE.get('cComponent').getContent(); //content at this point is <p>test</p>
valueToDisplay = content;
If I do:
jQuery(selector).html(valueToDisplay);
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p>
Has anyone ever seen this before using Firefox 3.6.10 and jQuery 1.4.2, I am trying to change a link text using the result from a jQuery ajax call.
I get the result expected from the ajax call:
function getValueToDisplay(fieldType){
var returnValue;
jQuery.ajax({
type: "GET",
url: "index.cfm",
async:false,
data: "fieldtype="+fieldType,
success:function(response){
returnValue = response;
}
});
return returnValue;
}
If I check the value at this point I get the expected value
console.log(returnValue) //output this --> <p>Passport Photo</p>
However when I use jQuery(selector).html to insert it inside of an existing anchor
I get:
<p><a xmlns="http://www.w3.org/1999/xhtml">Passport Photo</a></p>
I have been trying to figure out where that xmlns anchor is added but can't narrow it down to anything specific.
EDIT: I have tried forcing dataType:"html" in the ajax call...no change.
Your selector represents something that is, or is in an a tag.
A much more minimal version of your problem would be:
html:
<a id="test"></a>
js:
$('#test').html('<p>test</p>');
result:
<a id="test"><p><a xmlns="http://www.w3.org/1999/xhtml">test</a></p></a>
Change things around so you aren't putting p tags in an a tag, or do the following:
$('#test').empty().append('<p>test</p>');
I would like to extend the answer, as of why is happening, and provide a workaround.
Doing a GreaseMonkey script i was trying to change the content of an element, perhaps not changing per se but adding more elements as the tag had only an IMG inside.
Original:
<a onclick=something><img src=url></a>
What i tried to do was to insert a DIV element that would wrap the already IMG and another new SPAN second child, so the objetive was to end up with this:
<a onclick=something><div><img src=url><span>text</span></div></a>
Using the innerHTML property it would be like this:
ANode.innerHTML = '<div>' + ANode.innerHTML + '<span>text</span></div>';
but instead i got:
<a onclick=something><div><a xmlns="http://www.w3.org/1999/xhtml"><img src=url><span>text</span></a></div></a>
Looking at the answers here did help a bit although there's no real explanation. After a while i noticed something that does not happens with the example in the question, which now i believe is the key to this issue. I was the same as jfrobishow thinking where was it happening, i thought there was something wrong concatenating the ANode.innerHTML.
Answering, at the original question, the part of narrowing it down to where does this happens, notice that the out-of-nowhere <A> was enclosing both the IMG and the new SPAN nodes, so this made me curious, the unwanted <A> was being added just before the DIV element was "built". So from this, the original example, and my following workaround you can notice that this happens when you insert a new BLOCK node inside an Anchor, as both DIV and P (original example) elements are BLOCK elements.
(If you don't know what i mean by BLOCK is from the display property of an element http://www.w3schools.com/cssref/pr_class_display.asp)
The obvious workaround is to replace the type of node you're inserting, to a non-block element, in my case the problem was the DIV i wanted, but of course it depends on the objective of your script, most of the things are there by design, i put a DIV because i needed it, so i fixed it turning that DIV into another SPAN ( which is an inline element) but i still needed to behave like a block element so put the style, this is what worked for me:
ANode.innerHTML = '<span style="display:block;">' + ANode.innerHTML + '<span>text</span></span>';
So, plainly, this problem is not from scripting (Javascript for me) but from style (CSS) stuff.
BTW, this happened at Firefox 3.6.18, notice this does not happens at Firefox 5.0.
The problem is placing block elements inside an anchor tag.
This is not valid HTML, even though most browsers will parse it fine.
You just need to use a <span></span> element inside the anchor, instead of a <div> or <p>.
This is happening because in your <html> you declared a XML Namespace (xmlns). If the xmlns anchor is not breaking anything, just leave it there.
Also, don't use async:false, make a callback function to be called on success.
EDIT: Actually that just fixed the issue with that particular value... it started happening on other values where it used to be fine.
Somehow this fixed the issue.
Changed
jQuery(selector).html(valueToDisplay)
to
jQuery(selector).html(
function(index, oldHtml)
{
return valueToDisplay;
}
);
According to the doc, if I read it right it should be doing the same thing as I am not using oldHtml in the function. (http://api.jquery.com/html/).
From the doc: "jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content."
Try changing dataType in your ajax call to "text"
Using .append() instead of .html() fixed the issue for me. Never seen this before today. Why is it adding the extra xmlns? I tried changing my dataType to "text" as well, but it didn't work. It was really messing up my CSS styles as well, but using .append() completely resolved the issue. Thanks!
UPDATE: I needed to completely replace the content of my div with the result of an .ajax() query. .append() by itself wasn't sufficient, as it would just add to the content, so I found another workaround:
First clear the div:
$("#myDiv").html("");
Then, append the content using .append():
$("#myDiv").append("My content");
It's not perfect, but it works.

Javascript getElementById - reading works, altering doesn't

So, I have this pretty complex ajax thing going.
It loads new html (including div tags and all) to show up on the page.
I included a 'more' link to load additional data.
This more link links to my javascript function. The 'more' link is located in a div, which I gave a unique id. The next time the load function is called, I use document.getElementById(the id).style.display="none"; to "remove" this div from the look of the page.
I set error traps for this, the div with that id is found without problems, but javascript fails to change my style property.
I tested alert(document.getElementById(the id).innerHTML); and that worked without problems - hence the title of the question.
So, does anyone have any ideas/do I need to offer more information? The main problem is that it doesn't throw any errors anywhere, yet it fails to complete the task I asked...
Here's a bit of code to go with it -
try
{
var myidthing = "morelink" + ContentStart.toString(); //the id is correct
var div = document.getElementById(myidthing);
if (!div)
{
}
else
{
div.style.display="none"; //this doesn't work, but doesn't raise an error
alert(div.innerHTML); //this works without problem
}
}
catch(theerr)
{
alert(theerr);
}
------------------------->EDIT<-------------------------
I'm incredibly sorry if I upset any people.
I'm also angry at myself, for it was a stupid thing in my code. Basically, I had a variable that stored the contents of a parent div. Then I (succesfully) removed the div using the removeChild() method. Then my code pasted the contents of that vaiable (including the div I wanted gone) back into the parent div.
I switched around the order and it works fine now.
Again, excuse me for this.
Throwing out a few ideas of things to look for:
You said the div is generated by javascript. Is it possible the div you are targeting is not the one you think you are? It could be you are targeting another div, which is already hidden, or obstructed... or maybe the innerHTML you are displaying goes with a different element than the one you intend to target. Put an alert or script breakpoint in the if(!div) case, also, and see if it's going down that path.
If the above code is only a stripped-down version of your actual code, check your actual code for typos (for example: style.display = "none;";)
Using the FireBug plugin for FireFox, inspect the target element after the operation completes, and make sure that the display: none appears in the style information. If not, use FireBug's debugger to walk through your javascript, and see if you can figure out why.
Use FireBug to break on all script errors, in case there is another error causing this behavior.
Try empty quotes instead of 'none' and see if that works?:
document.getElementById('element_id').style.display="";
Failing that, don't change the style, just add a class which hides the element.

Why does jQuery fail to hide certain HTML?

I've been running my head into a wall trying to figure this out. Take the following HTML body:
<body>
<div id="project">
<h1>Hi</h1>
<h2>Hello</h2>
</div>
</body>
And the following jQuery code:
$(function(){
var h = $('#project').html();
$('#project').remove();
$(h).hide().appendTo('body');
alert("Created HTML, hide, and appended!");
});
The $(h).hide() portion causes jQuery to throw an exception in Safari 4 and Firefox 3.5.
Safari: TypeError: Result of expression 'this[a].style' [undefined] is not an object.
Firefox: uncaught exception: [Exception... "Could not convert JavaScript argument arg 0" nsresult: ...]
When I change the HTML to contain just one of the two headings (if you remove the <h1> or <h2> from the HTML, the script runs successfully. Why is this?
To try for yourself, see http://jsbin.com/avisi/edit
Edit: I'm not actually trying to remove and element from the DOM and re-insert it by copying the HTML. This is just a test case for an error I'm having in more complex code, and I'm trying to understand why this error occurs. I agree that, if I wanted to accomplish just what is shown here, I would use something like $('#project').remove().children().appendTo('body')
I cannot duplicate your error in Firefox. However, you might want to try cleaning it up with the following:
$('#project').remove().children().appendTo('body').hide();
Broken down, this is what's happening
// Get the `project` container
$('#project')
// Remove it from the page
.remove()
// Get its children (the h1, h2, etc)
.children()
// Append those nodes to the body
.appendTo('body')
// Hide those nodes
.hide();
Others are proposing that .hide() is causing problems since the node that it is being applied to is not part of the main document; however, this is just not the case. As long as you maintain a reference to any node, you can affect its style property (via hide, show, etc).
One things you might want to check is to make sure that $('#project') is actually returning the (if any) expected node. Problems may arise otherwise.
So I poked around in Safari and found your problem. Here's a dump from the developer console.
> var h = $('#project').html();
undefined
> var t = $(h);
undefined
So far, so good. undefined here simply means that the statement (the var statement) has no return value (which it doesn't)
> t.hide()
ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js:131TypeError: Result of expression 'this[a].style' [undefined] is not an object.
Here's the error that you described. Inspecting each item in jQuery object will reveal the error below
> t[0]
<h1 style=​"display:​ none;​ ">​Hi​</h1>
Good...
> t[1]
(whitespace)
Dammit. Really? Here's the problem. whitespace nodes have no style attribute, which is what's causing the problem.
> t[2]
<h2>​Hello​</h2>
This is why copying the HTML of one node to another just to move those nodes is a bad technique. I suggest you use the snippet that I provided above.
There's a text node being selected in the $(h). We can filter that out using the filter function though.
This should work (I've only tested in FF though):
$(function(){
var h = $('#project').html();
$('#project').remove();
$(h).filter("*").hide().appendTo('body');
alert("Created HTML, hide, and appended!");
});
Pretty wierd behaviour IMO.
You removed the contents from the DOM before, so there is nothing to hide. If you would do
$(h).appendTo('body').hide();
it should work

What exactly can cause an "HIERARCHY_REQUEST_ERR: DOM Exception 3"-Error?

How exactly does it relate to jQuery? I know the library uses native javascript functions internally, but what exactly is it trying to do whenever such a problem appears?
It means you've tried to insert a DOM node into a place in the DOM tree where it cannot go. The most common place I see this is on Safari which doesn't allow the following:
document.appendChild(document.createElement('div'));
Generally, this is just a mistake where this was actually intended:
document.body.appendChild(document.createElement('div'));
Other causes seen in the wild (summarized from comments):
You are attempting to append a node to itself
You are attempting to append null to a node
You are attempting to append a node to a text node.
Your HTML is invalid (e.g. failing to close your target node)
The browser thinks the HTML you are attempting to append is XML (fix by adding <!doctype html> to your injected HTML, or specifying the content type when fetching via XHR)
If you are getting this error due to a jquery ajax call $.ajax
Then you may need to specify what the dataType is coming back from the server. I have fixed the response a lot using this simple property.
$.ajax({
url: "URL_HERE",
dataType: "html",
success: function(response) {
$('#ELEMENT').html(response);
}
});
Specifically with jQuery you can run into this issue if forget the carets around the html tag when creating elements:
$("#target").append($("div").text("Test"));
Will raise this error because what you meant was
$("#target").append($("<div>").text("Test"));
This error can occur when you try to insert a node into the DOM which is invalid HTML, which can be something as subtle as an incorrect attribute, for example:
// <input> can have a 'type' attribute
var $input = $('<input/>').attr('type', 'text');
$holder.append($input); // OK
// <div> CANNOT have a 'type' attribute
var $div = $('<div></div>').attr('type', 'text');
$holder.append($div); // Error: HIERARCHY_REQUEST_ERR: DOM Exception 3
#Kelly Norton is right in his answer that The browser thinks the HTML you are attempting to append is XML and suggests specifying the content type when fetching via XHR.
It's true however you sometimes use third party libraries that you are not going to modify. It's JQuery UI in my case. Then you should provide the right Content-Type in the response instead of overriding the response type on JavaScript side. Set your Content-Type to text/html and you are fine.
In my case, it was as easy as renaming the file.xhtml to file.html - application server had some extension to MIME types mappings out of the box. When content is dynamic, you can set the content type of response somehow (e.g. res.setContentType("text/html") in Servlet API).
You can see these questions
Getting HIERARCHY_REQUEST_ERR when using Javascript to recursively generate a nested list
or
jQuery UI Dialog with ASP.NET button postback
The conclusion is
when you try to use function append, you should use new variable, like this example
jQuery(function() {
var dlg = jQuery("#dialog").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form:first"));
});
In the example above, uses the var "dlg" to run the function appendTo.
Then error “HIERARCHY_REQUEST_ERR" will not come out again.
I encountered this error when using the Google Chrome extension Sidewiki. Disabling it resolved the issue for me.
I'm going to add one more specific answer here because it was a 2 hour search for the answer...
I was trying to inject a tag into a document. The html was like this:
<map id='imageMap' name='imageMap'>
<area shape='circle' coords='55,28,5' href='#' title='1687.01 - 0 percentile' />
</map>
If you notice, the tag is closed in the preceding example (<area/>). This was not accepted in Chrome browsers. w3schools seems to think it should be closed, and I could not find the official spec on this tag, but it sure doesn't work in Chrome. Firefox will not accept it with <area/> or <area></area> or <area>. Chrome must have <area>. IE accepts anything.
Anyway, this error can be because your HTML is not correct.
I know this thread is old, but I've encountered another cause of the problem which others might find helpful. I was getting the error with Google Analytics trying to append itself to an HTML comment. The offending code:
document.documentElement.firstChild.appendChild(ga);
This was causing the error because my first element was an HTML comment (namely a Dreamweaver template code).
<!-- #BeginTemplate "/Templates/default.dwt.php" -->
I modified the offending code to something admittedly not bulletproof, but better:
document.documentElement.firstChild.nodeType===1 ? document.documentElement.firstChild.appendChild(ga) : document.documentElement.lastChild.appendChild(ga);
If you run into this problem while trying to append a node into another window in Internet Explorer, try using the HTML inside the node instead of the node itself.
myElement.appendChild(myNode.html());
IE doesn't support appending nodes to another window.
This ERROR happened to me in IE9 when I tried to appendChild an dynamically to a which already existed in a window A. Window A would create a child window B. In window B after some user action a function would run and do an appendChild on the form element in window A using window.opener.document.getElementById('formElement').appendChild(input);
This would throw an error. Same with creating the input element using document.createElement('input'); in the child window, passing it as a parameter to the window.opener window A, and there do the append. Only if I created the input element in the same window where I was going to append it, it would succeed without errors.
Thus my conclusion (please verify): no element can be dynamically created (using document.createElement) in one window, and then appended (using .appendChild) to an element in another window (without taking maybe a particular extra step I missed to ensure it is not considered XML or something). This fails in IE9 and throws the error, in FF this works fine though.
PS. I don't use jQuery.
Another reason this can come up is that you are appending before the element is ready e.g.
<body>
<script>
document.body.appendChild(foo);
</script>
</body>
</html>
In this case, you'll need to move the script after the . Not entirely sure if that's kosher, but moving the script after the body doesn't seem to help :/
Instead of moving the script, you can also do the appending in an event handler.
I got that error because I forgot to clone my element.
// creates an error
clone = $("#thing");
clone.appendTo("#somediv");
// does not
clone = $("#thing").clone();
clone.appendTo("#somediv");
Just for reference.
IE will block appending any element created in a different window context from the window context that the element is being appending to.
e.g
var childWindow = window.open('somepage.html');
//will throw the exception in IE
childWindow.document.body.appendChild(document.createElement('div'));
//will not throw exception in IE
childWindow.document.body.appendChild(childWindow.document.createElement('div'));
I haven't figured out how to create a dom element with jQuery using a different window context yet.
I get this error in IE9 if I had disabled script debugging (Internet Explorer) option. If I enable script debugging I don't see the error and the page works fine. This seems odd what is the DOM exception got to do with debugging either enabled or disabled.

Categories

Resources