Skip to content

Instantly share code, notes, and snippets.

@fabiomcosta
Created August 7, 2010 14:50
Show Gist options
  • Save fabiomcosta/512871 to your computer and use it in GitHub Desktop.
Save fabiomcosta/512871 to your computer and use it in GitHub Desktop.
/*
---
script: Elements.From.js
description: Returns a collection of elements from a string of html.
license: MIT-style license
requires: [Element]
provides: [Elements.from]
...
*/
(function(){
var reFirstTag = /\s*<([^\s>]+)/;
var divContainer = new Element('div');
var translations = {
option: [1, '<select multiple="multiple">', '</select>'],
tbody: [1, '<table>', '</table>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
td: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.th = translations.td;
translations.optgroup = translations.option;
translations.thead = translations.tfoot = translations.tbody;
Elements.extend('from', function(text, excludeScripts, filter){
if (excludeScripts === false) text = text.stripScripts();
var match = text.match(reFirstTag),
firstTag = match ? match[1].toLowerCase() : '',
firstTagTranslation = translations[firstTag],
container = divContainer;
if (firstTagTranslation){
container.set('html', firstTagTranslation[1] + text + firstTagTranslation[2]);
for (var i = firstTagTranslation[0]; i--;) container = container.firstChild;
container = $(container);
} else {
container.set('html', text);
}
return container.getElements(filter || '>');
});
})();
@assertchris
Copy link

firstTag = match ? match[1].toLowerCase() : '',
Shouldn't this be == ?

@fabiomcosta
Copy link
Author

no, its correct. firstMatch will receive match[1].toLowerCase() if match is truthy else it will receive ''.
Ty very much for reviewing

@fabiomcosta
Copy link
Author

firstTag*

@assertchris
Copy link

Oh, well now I feel dumb. I blame lack of sleep! :) Makes perfect sense...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment