Peter
Peter

Reputation: 501

jQuery filter tags and join as html

For example I have HTML code:

aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong>  <a href="d">aaaa</a>

And I would like leave only div.inptag tag, and remove all other tags, but leave innerText from other tags.

I wrote jQuery code:

dat = $('<div/>').html('aaa<b>aaa</b><div class="inptag">ccc</div>')
.find('*:not(div.inptag,div.inptag>div.typ,div.inptag>input)').contents().unwrap();

...and I don't know how get result as standard HTML code. Now I have [object Object] and .join('') not working.

Upvotes: 0

Views: 170

Answers (1)

Ixonal
Ixonal

Reputation: 646

I'm assuming you want a string as output here? If so, this looks to accomplish what you need.

var inputStr = 'aaa<b>aaa</b><div class="inptag">ccc</div> ccc cc <strong>zczczc</strong>  <a href="d">aaaa</a>', 
    elt = $('<div/>').html(inputStr), //jquery will convert this to DOM elements
    badTags = elt.find(':not(div.inptag)'), //find the elements that are not divs with a class of inptag
    index,
    outputStr = '' + inputStr; //making a copy of inputStr

//cycle through all of the bad tags that we found
for(index = 0; index < badTags.length; index++) {
    //replace any instances of the outer html with instances of the inner text
    outputStr = outputStr.replace(badTags[index].outerHTML, badTags[index].innerText);
}

alert(outputStr);

fiddle here.

Upvotes: 1

Related Questions