Javascript Jquery html()问题

Javascript Jquery html()问题,javascript,jquery,Javascript,Jquery,我正试图用以下代码将html标记放入我的数组 //my htmlData which is entered by user so it could be varies. <em>test</em> here for the testing purpose second line <strong>texts</strong> here 但是我得到一个错误,说uncaughttypeerror:cannotcallmethod'trim'of nul

我正试图用以下代码将
html
标记放入我的
数组

//my htmlData which is entered by user so it could be varies.
<em>test</em> here for the testing purpose
second line <strong>texts</strong> here
但是我得到一个错误,说
uncaughttypeerror:cannotcallmethod'trim'of null。

不确定为什么
$(this).html()
会返回一个
null


有人能帮我吗?非常感谢

文本节点没有
innerHTML
属性。

应该是
文本节点的问题。
因为它们没有
innerHTML
属性 试着过滤掉它们

var data = [];
$(htmlData).contents().each(function(){
     var nodeType = this.nodeType;
     if(nodeType === 1) { // Will only select element nodes
        data.push($.trim($(this).html()));
     } 
     else if(nodeType === 3) {
        data.push($.trim(this.nodeValue));
     }
}

您可以使用
.nodeValue
访问etext节点的数据

假设$(htmlData).contents()返回有效的jQuery对象,请使用$.trim($(this).html())而不是.trim()

谢谢,但您的代码将只保留标记文本,但删除用户输入的纯文本+1@FlyingCat基于此,您可以推送不同的内容(nodeValue或textContent),具体取决于节点类型是否为element。@FlyingCat。。您可以使用
nodeValue
阅读文本内容node@Sushanth我有一个后续问题。是否可以将带有html标记的文本存储到数据数组中?我现在所做的只是测试,而不是测试
var data = [];
$(htmlData).contents().each(function(){
     var nodeType = this.nodeType;
     if(nodeType === 1) { // Will only select element nodes
        data.push($.trim($(this).html()));
     } 
     else if(nodeType === 3) {
        data.push($.trim(this.nodeValue));
     }
}