Use jQuery to wrap text after element

谁说我不能喝 提交于 2019-12-07 03:54:08

问题


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.


回答1:


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>');
});


来源:https://stackoverflow.com/questions/34834061/use-jquery-to-wrap-text-after-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!