bar

Use jQuery to wrap text after element

What I have:

Checkmark inside the label.

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

What I need:

Using jQuery, I need to wrap the text after the checkbox (ie "bar") in the span element.

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

What I tried:

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

This does not exclude the check box if required.

+4
source share
1 answer

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

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

, , node input, sibling node nextSibling:

$('label input').each(function () {
  $(this.nextSibling).wrap('<span></span>');
});
+7

Source: https://habr.com/ru/post/1624630/


All Articles