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.
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/
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With