Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and append without adding space

Tags:

jquery

append

I have the code:

<div class="message">
    <span>Menu 1</span><span>Menu 2</span>
</div>

Note: between the span tags don't have spaces. If I use:

$('.message').append('<span>Menu 3</span>');

The append adds a space in the line. Is there any other way to put a tag without having to add space?

I need the jquery generates a code like this:

<div class="message">
    <span>Menu 1</span><span>Menu 2</span><span>Menu 3</span>
</div>

Thank you.

like image 795
André Golvea Avatar asked Aug 13 '12 16:08

André Golvea


2 Answers

This fixes the problem:

$('.message span:last-child').after('<span>Menu 3</span>');​

jQuery was appending your new item after the line break. Using span:last-child will select the last menu item and then using .after() will add the new item directly after it.

Please note that this will not work if .message is currently empty. You would need to check for this and use your current code in that case to add the first element.

See the result here: http://jsfiddle.net/ZbSCU/

like image 101
David Thibault Avatar answered Sep 21 '22 11:09

David Thibault


You could remove the whitespace nodes from your initial html:

$('.message').contents().each(function() {
    if (this.nodeType === 3 && !$.trim(this.nodeValue)) {
        $(this).remove();
    }
});​

$('.message').append('<span>Menu 3</span>');

Now, unless you explicitly add whitespace yourself dynamically, there should be none.

http://jsfiddle.net/ktEMx/5/

The html representation after this treatment is:

<div class="message"><span>Menu 1</span><span>Menu 2</span><span>Menu 3</span></div>
like image 43
Esailija Avatar answered Sep 24 '22 11:09

Esailija