CSS-string to jQuery object

CSS-selectors are clean and clear, element#id.class.another-class. But why, if we want to create an element, do we have to do this?

I build a css parser that converts a css-selector into a jQuery object. For now, only node-type, id and classes are implemented.

Creating an element is now a piece of cake.

The wins might not be as astronomical as I make it sound, but in future posts I might come up with some handy uses for this code.

innerHTML in IE

I stumbled upon an interesting issue today. Internet Explorer seems to store its references to DOM elements in another way than Chrome or Firefox. A (vanilla) javascript-object of an element is linked to the element in the DOM. In Chrome and Firefox, when that element is removed from the DOM, the HTML for it still exists in the innerHTML attribute in the js-object, but in IE the innerHTML is cleared.

The Problem

We have the next example (jsfiddle):

An elment is created, text is added and it is appended to the body. When we clear the body, by replacing its HTML with nothing, in IE, the html of the element is also emptied.

The Cause

Javascript in IE seems to hold reference to the ‘real’ HTML in the DOM and its values depend on it. So, when the html is not available in the DOM, its not in the object. This is more logical than you might think. The innerHTML attribute in the object is just holding a string of HTML-code, not any objects of the inner elements. When the content is cleared, so is the innerHTML, to keep the attribute’s value up to date.
Chrome and Firefox, however, keep their reference to the content. Which will leave the element intact when you remove it from the DOM, so it can be added later in the process.

The Fix

To fix this issue, the innerHTML shouldn’t be cleared. An alternative is to remove the elements from, in this example, the body by using removeChild.

This loop will remove all elements in the body, which has the same effect as clearing the innerHTML. The difference is, that the HTML is not really removed. It is still accessible in the javascript object.

jQuery: html vs empty

Maybe this issue doesn’t seem that common, but using jQuery you might run into it. jQuery uses both ways to clear the content of an element. The first is used in the html method and the second in the empty method. When using front-end mvc’s, like Backbone, there are situations where you want to re-render a view without re-rendering it’s sub-view. By first emptying the view’s html, the element will be left intact.