Jonathan Hendler
Jonathan Hendler

Reputation: 1259

Why does the following way of creating DOM elements not work with jQuery in IE7 and IE8?

Sometimes, it is useful to create DOM elements as jQuery objects for use as selectors and context.

The following works in both IE7,IE8 and all other browsers using jQuery 1.6.2/3 - but note that document.createElement is used to make this work.in IE7 and IE8.

   jQuery('body').append('<div id="basic-render-test"> </div>');

   var new_object = {};
   new_object.wrapper = '<span id="adfasdfasdfwersadfas3rs">';
   //alert(typeof new_object.wrapper);

   if (jQuery.browser.msie && jQuery.browser.version <= 8.0){ 
       new_object.el = document.createElement(new_object.wrapper);
   } else  {
       new_object.el = jQuery(new_object.wrapper);
   }

   new_object.render_into = "#basic-render-test";
   jQuery(new_object.render_into).append( new_object.el );
   some_html = '<DIV id="type-m" class="translate"> HELLO IE</DIV>';
   jQuery(new_object.el).html( some_html );

The declared DOM type is HTML 5

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Upvotes: 3

Views: 1378

Answers (2)

jfriend00
jfriend00

Reputation: 707308

In looking at the jQuery code, it takes a different code path if what you pass to the jQuery function is a simple tag like "<span>" vs. what you're passing. When it's a simple tag, jQuery calls createElement() on it, pretty much like your workaround code. When it's not a simple tag, jQuery calls createDocumentFragment() and then takes a lot more complicated path involving a temporary div, setting your HTML into the innerHTML, etc...

If you make your HTML be a simple tag and then add the id attribute to the object after it's created, it should follow the createElement code path.

To work-around this, change this:

new_object.wrapper = '<span id="adfasdfasdfwersadfas3rs">';

to this:

new_object.wrapper = '<span id="adfasdfasdfwersadfas3rs"></span>';

From this jQuery documentation:

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag.

Your HTML was not paired with a closing tag.

Upvotes: 2

Lepidosteus
Lepidosteus

Reputation: 12037

You need to provide an actual valid html code for it to be created properly. In your exemple, your span tag is not closed, which result in an invalid code at evaluation in IE while other browsers tend to fix it automagically.

Replace

new_object.wrapper = '<span id="adfasdfasdfwersadfas3rs">';

With

new_object.wrapper = '<span id="adfasdfasdfwersadfas3rs"></span>';

This exemple runs perfectly on both IE 7 and 8

Upvotes: 6

Related Questions