FlyingCat
FlyingCat

Reputation: 14250

How to store html markup to an array

I have a following question from my last post.

Jquery html() issue

I want to store each node as full html markup.

The data array should be something like

['<em>test</em>', 'here for the testing purpose',
'second line', '<strong>texts</strong>', 'here']

The codes I have now:

if(this.nodeType === 3) { // Will only select element nodes
    data.push($(this).text());
}else if(this.nodeType === 1){
    data.push($(this).html());
}

but it only store

['test', 'here for the testing purpose','texts','here'] 

Is it possible to store the html markup as well?

Thanks so much!

Upvotes: 2

Views: 2656

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

Replace

data.push($(this).html());

with

data.push(this.outerHTML);

Remember

this -- DOM object

$(this) -- jQuery Object

Try using DOM objects instead of jQuery objects whenever possible as the former are a bit faster, because it eliminates an extra overhead of converting them to latter and then apply a method.. Should not be a big deal but just for info.

Upvotes: 3

McGarnagle
McGarnagle

Reputation: 102753

element.outerHTML returns the markup including the outer tags of the element:

data.push(this.outerHTML);

Upvotes: 2

Related Questions