jquery 如何替换 test 节点变为一个标签?

代码如下,如何把下面代码中Guest - Guest 增加一个A标签?目前只知道如何取这个值.我想把html 中所有没有被包装成标签的都给包一层,这样可以便于后续操作

<li id="test" value="0">
    Guest - Guest
    <ul class="task-list">
        <li>Role = $everyone, $unauthenticated</li>
        <li>
            Has access to the "List projects" function, but none of the others
        </li>
    </ul>
</li>
var test=$("#test").contents().filter(function() {//取值
    return this.nodeType === 3;
    })[0].nodeValue;
阅读 2.5k
2 个回答
var test=$("#test").contents().each(function(index,node) {//取值
    if(this.nodeType === 3){
        $(this).wrap("<a class=\"wrap\"> </a>");
    };
});

demo

@Wenci丶 的回答已经可行了,不过可以改成 filter 实现的,另外,看你的意思应该是想包个 <span> 而不是 <a> 吧。

$("#test").contents()
    .filter((i, node) => {
        return node.nodeType === 3;
    })
    .wrap("<span>");

https://jsfiddle.net/9m8Lqcbj/

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题