Remove formatting except for a specific class

I am trying to remove all html formatting inside a <div> except for a specific class.

I tried

 $('div#text :not(a.keep)').contents().each(function () { $(this).html($(this).text()); }); 

But this does not change the content of the div.

sample input: <span>a </span><span><a class="keep">b</a></span> c

a <a class="keep">b</a> c result: a <a class="keep">b</a> c

WHY?

Why am I trying to do this? I have a div, contenteditable, and I want to format what the user types. I have a timer, and every few seconds I check the contents of the div to find the material to format, but I want to save what was marked for saving.

+4
source share
2 answers

The problem is that your .keep can be anywhere (deep) in your element

Here's an alternative approach.
The idea is to get all the elements that your #text and THEN contains, scroll through each one to make sure it matches your requirements.

Here is a sample

 function getChildrenDeep(elem) { var ret = []; $(elem).each(function(k,v){ ret.push(v); if ($(v).children().length > 0) ret = $.merge(ret,getChildrenDeep($(v).children())); }); return ret; } var plainChildren = getChildrenDeep($("#text")), final = ''; $(plainChildren).each(function(k,v){ if (!$(v).hasClass("keep")) final += $(v).clone().children().remove().end().text(); /* See Reference */ else final += $(v)[0].outerHTML; }); document.write(final); 

http://jsfiddle.net/5hjnX/4/

Link

0
source

you can use non selector function.

 $('div#text').not(a.keep).contents().each(function () { $(this).html($(this).text()); }); 

however, calling contents() seems somehow weird that it will return text nodes as well as html nodes and see that you are trying to set the html property of every selected element that seems odd (there is no html to set to text node)

if you want to take all the text of the node and replace any html in this node with text content only, then change to

 $('div#text').not(a.keep).children().each(function () { $(this).html($(this).text()); }); 

but if this is what you are trying to accomplish, I would recommend

 $('div#text').not(a.keep).children().each(function () { var text = $(this).text(); $(this).empty().html(text); }); 

because it’s easier to see the intention. This does not solve the recursion problem if you can have a.keep nested in one of the selected elements

+1
source

Source: https://habr.com/ru/post/1439148/


All Articles