HelpMe
HelpMe

Reputation: 35

JQuery: Multiple selectors, doing something only with one of them

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?

Upvotes: 2

Views: 528

Answers (2)

bobince
bobince

Reputation: 536765

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()}));
});

Upvotes: 2

gblazex
gblazex

Reputation: 50137

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.

Upvotes: 1

Related Questions