-1

I am trying to put the html markup into my array with the following codes

//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

I want to store them in my array by using

var data = [];
$(htmlData).contents().each(function(){
           data.push($(this).html().trim());
     }

but I got an error saying Uncaught TypeError: Cannot call method 'trim' of null.

Not sure why $(this).html() would returns a null.

Can anyone help me here? Thanks a lot!

3 Answers 3

1

Should be the issue with the text nodes. As they do not have the innerHTML property Try filtering them out

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

You can use .nodeValue to access the data of th etext node

Sign up to request clarification or add additional context in comments.

4 Comments

thanks but your codes will only keep the markup texts but remove plain texts that users enter. +1
@FlyingCat Based on this you can push something different (nodeValue or textContent) depending if the node type is element or not.
@FlyingCat .. You can use nodeValue to read the content of the text node
@Sushanth I have a follow up question. Is that possible I can store texts with html markup into data array? what I have now only test but not <em>test</em>
1

Assuming that $(htmlData).contents() returns a valid jQuery object, use $.trim($(this).html()) instead of .trim()

Comments

0

Text nodes don't have innerHTML properties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.