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?
1 2 3 4 5 |
$('<div id="id" class="class another-class">'); // or $('<div>').attr({ id: 'id', class: 'class another-class' }) |
I build a css parser that converts a css-selector into a jQuery object. For now, only node-type, id and classes are implemented.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
$.fn.parse = function(selector) { var len = selector.length, id, cls = '', prev; // We need to search the selector // backwards so we can get the parts more easily selector // Reverse the string .split('') .reverse('') .join('') // Execute the function for every # (id) and . (class) .replace(/#|\.g/, function(ch, i) { // The index is from the reversed string, // We need to re-reverse it i = len - i; // Get the part from the selector, start at the index (. or #) // until the index of the previous part var substr = selector.substr(i, prev - i || undefined); // Is it a class or an ID? if('.' == ch) cls += substr + ' '; else // The id will only be set once; the last id in the selector id = id || substr; // Reset the previous index prev = i - 1; }); // Create the element by the remaining part, // or make it a div, and append the ID and class return $('<' + (selector.substr(0, prev) || 'div') + '>') .attr({ id: id, class: cls }); } |
Creating an element is now a piece of cake.
1 2 3 4 5 6 7 |
// Create a nav-element var $el = $().parse('nav#menu.user-nav.dropdown'); // This will result in a jQuery-object representing: // |
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.