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:
Broken down, this is what’s happening
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 (viahide,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.
So far, so good.
undefinedhere simply means that the statement (thevarstatement) has no return value (which it doesn’t)Here’s the error that you described. Inspecting each item in jQuery object will reveal the error below
Good…
Dammit. Really? Here’s the problem. whitespace nodes have no
styleattribute, which is what’s causing the problem.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.