Reputation: 1793
See http://jsfiddle.net/PAWAS/3/
JavaScript:
$(document).ready(function () {
$.each($(".item"), function(index, value) {
thisEl = $(this);
thisEl.children("strong").after("<span style='display:inline-block'>");
$("</span>").appendTo(thisEl);
});
});
HTML:
<div class="item">
<strong>Time Cond:</strong>
MorningCheck
</div>
Should be:
<div class="item">
<strong>Time Cond:</strong>
<span> MorningCheck</span>
</div>
But the </span>
gets injected before the text MorningCheck
What did I do wrong?
Upvotes: 1
Views: 83
Reputation: 816462
.append
and .appendTo
manipulate the DOM, the don't create HTML strings. Have a look at a similar question and my answer here: Using .append() with lists places text on a newline.
Assuming there is always only one (non-empty) text node inside the element, you can use the following to put it inside a span
element:
$(".item").each(function() {
// get all child nodes, including text nodes
$(this).contents().filter(function() {
// is text node and does not only contain white space characters
return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
}).wrap('<span style="display:inline-block"></span>'); // wrap in span
});
This looks for non-empty text nodes and wraps them inside a span
element. If there are multiple text nodes, you might only want to get the .last()
of them, or if you want to target the text node after the strong
element in particular, you could do:
$($(this).children('strong').get(0).nextSibling).wrap(...);
Upvotes: 2