Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $() work differently in Internet Explorer?

I am running the following JavaScript in both Firefox Developer Edition 38 and Internet Explorer 8 and 9.

console.log('+++++++++++++++++++++++++++++++');
console.log('jquery version = ' + $.fn.jquery);
var myHtmlString = "<!-- my comment -->" +
                      "<optgroup label='my label'>" +
                        "<option value='1'>option one</option>" +
                      "</optgroup>";

console.log($(myHtmlString));
console.log($(myHtmlString)[0]);
console.log($(myHtmlString)[1]);
console.log($(myHtmlString).length);

In Firefox, I get:

enter image description here

In IE, I get:

enter image description here

So, apparently in Firefox, an HTML comment is getting added in as an element of this object but in IE, it's not. Why is this behaving this way, is there a bug, or is there another way I should be creating this object?

NOTE: I tried $.parseHTML(myHtmlString) but it does the same thing.

UPDATE: This answer How does jQuery treat comment elements? provides a potential workaround.

like image 748
kleaver Avatar asked Apr 02 '15 16:04

kleaver


People also ask

How do I use Compatibility View in Internet Explorer?

Open Internet Explorer, select the Tools button , and then select Compatibility View settings. Under Add this website, enter the URL of the site you want to add to the list, and then select Add.

Is ES6 compatible with Internet Explorer?

ECMAScript 2015 (ES6) is Partially Supported on Internet Explorer 11. If you use ECMAScript 2015 (ES6) and your users are using Internet Explorer 11, then they would see the feature properly. That doesn't guarantee that other web technologies are also compatible in Internet Explorer 11 though.

What is compatibility settings in IE?

Compatibility View is a feature of Windows Internet Explorer 8 that enables the browser to render a webpage nearly identically to the way that Windows Internet Explorer 7 would render it.


1 Answers

So it depends on the browser you're using, but since you're passing in more than 1 simply tag, (as an example $('<div>example html creation</div>')) jQuery lets the browser handle the creation.

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in.

jQuery documentation

Firefox for example is looking through each of your < > areas, and it finds 2. While IE doesn't care, and processes it all as 1 (hence the length 1).

Long story short, you're doing it fine. That's just internally how the browser is handling it, you don't have to worry about any of that!

like image 104
Mark Pieszak - Trilon.io Avatar answered Oct 17 '22 21:10

Mark Pieszak - Trilon.io