Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to wrap text after element

What I have:

A checkbox inside a label.

<label for="foo">
  <input type="checkbox" id="foo" />bar
</label>

What I need:

Using jQuery, I need to to wrap the text following the checkbox (i.e. "bar"), in a span element.

<label for="foo">
  <input type="checkbox" id="foo" /><span>bar</span>
</label>

What I've tried:

$('label').wrapInner('<span></span>');

This does not exclude the checkbox as required.

like image 364
Clarus Dignus Avatar asked Jan 17 '16 01:01

Clarus Dignus


People also ask

What does the jQuery wrap () function do?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

Which jQuery method allows you to add a wrapper element around another set of elements?

jQuery wrap() Method The wrap() method wraps specified HTML element(s) around each selected element.

What is wrapped set in jQuery?

The wrapped set is simply a list of DOM elements(with their children) in the order in which they are defined in the current document that matches a selector or in the order in which they have been created on the fly with the $(html) function.


1 Answers

If you want to wrap the text node, you could filter the contents of the element based on whether the nodeType property is 3 (which is the value of a text node), and wrap the returned text node.

$('label').contents().filter(function () {
  return this.nodeType === 3;
}).wrap('<span></span>');

Alternatively, if you know the text node will always be the next sibling of the input element, you could select the next sibling node using the nextSibling property:

$('label input').each(function () {
  $(this.nextSibling).wrap('<span></span>');
});
like image 196
Josh Crozier Avatar answered Oct 02 '22 14:10

Josh Crozier