tags:

views:

59

answers:

2

Hi JQuery ninjas.

Hope you can help.

I'm looping through two selectors:

$('.div').each(function() {
    $('.selector1, .selector2 option:selected').text();
}

Both selectors returns plain-text and I need the output in the order of the page.

My problem is that whenever it is .selector2 (value from a dropdown) I need to add a < span > tag around it. How can I do that and at the same time keep the order?

+1  A: 

You need to use the wrap function.

.wrap( wrappingElement )

wrappingElementAn HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the matched elements.

.wrap( wrappingFunction )

wrappingFunctionA callback function which generates a structure to wrap around the matched elements.

galambalazs
+2  A: 

text() returns plain text with no markup. You shouldn't treat this as HTML, as you imply by ‘adding <span>’. Otherwise, < and & characters in the text will become markup, with potential security implications. Never mix up plain-text and HTML markup.

If you must throw HTML strings about, you could use html() instead:

var html= $('.selector1, .selector2 option:selected').map(function() {
    if ($(this).is('.selector1'))
        return $(this).html();
    else
        return '<span>'+$(this).html()+'</span>';
}).get().join('');

But I'd prefer to use DOM-like methods:

target= $('#place-to-put-content');
$('.selector1, .selector2').each(function() {
    if ($(this).is('.selector1'))
        $target.append(document.createTextNode($(this).text()));
    else
        target.append($('<span>', {text: $(this).val()}));
});
bobince
Thanks a lot. The text() was a mistake when I created the example. Im of course using html() since it is html I'm creating :) About solution 2: Would it be better to append at the end instead of in the loop? Performance wise...
HelpMe
It won't make any difference, as each DOM Node is inserted into the document one-by-one either way. The same happens using `append()` to insert a stretch of HTML. It's only when you can write the *whole* `html()` of an object in one go that you can get any speedup (and even then there are cases where you don't, due to jQuery's processing trying to hide bugs). In any case, unless you have *hundreds* of `.selector1, .selector2` elements in a single parent, it's not going to matter.
bobince
Just a quick update for your great solution, you miss .get() on the first solution before join()
HelpMe
Well spotted, thanks!
bobince