jquery:将标签和文本分开

jquery: separate tag and text

本文关键字:文本 标签 jquery      更新时间:2023-09-26

我有:

// $(this): <span class="class1"><span class="class2"></span> Some text</span>
$(this).children().each(function () {
    console.log(this);
});

从控制台我只得到了class2的跨度,我怎么能得到文本?类似于:

['<span class="class2"></span>', 'Some text']

$(this).children()将只返回作为元素的子节点。

您需要使用$(this).contents()来获取所有节点,包括文本节点。:)

然后,您可以过滤这些节点,只获取元素和文本(请参见节点类型):

$(this).contents().filter(function() {
  return (this.nodeType === 1) || (this.nodeType === 3);
})

注意.contents().children()之间的差异。您需要以前的

当.children()返回所有可用元素时,.contents也返回文本和注释

您可以获得这样的输出

jQuery(".class1").contents()