Remove all tags except for img tag
I need an regular expression or something else to remove all tags in a contentEditable
div
, but to keep img
tag with specific class
or id
, how I can do this?
Now I use:
.replace(/(<\/?.*?>)/gi, '');
but it removes all tags.
I made this 开发者_如何学运维:
var element = document.getElementById("myDiv").children;
for(var i=0; i<element .length;i++)
{
if(element[i].tagName != "IMG" || element[i].className != "requiredClassName")
{
element[i].parentNode.removeChild(element[i]);
}
}
var child=document.getElementById('editableDIV').firstChild;
while(child) {
var removeNode=null;
if(child.tagName&&(child.tagName.toUpperCase()!=='IMG'||
child.id!=='myid'||
child.className!=='myclass')) removeNode=child;
child=child.nextSibling;
if(removeNode)removeNode.parentNode.removeChild(removeNode);
}
( if you need plain JS ): Maybe the better way is to collect all elements then after check their class/id and perform action. Good idea is to use DOM, not regexp. DOM is for HTML elements manipulation.
( or use jQuery ): Simple code can do that thing. Just collect all div's children and check their class in .each() loop;
For e.g.:
$('#contentEditable').each( function( index ) {
if( !this.is( 'img' ) && ( this.is('.someclass') || this.is('#someid') ) ) {
this.remove();
}
});
Hope it helps you.
P.S.:
Be careful when you are using greedy quantification .*
It will get all text between any < >
, so if you have code listed below regexp (<\/?.*?>)
will collect whole code.
<div class="container">
<div id="header">
<div id="portalLink">
<a class="genu" href="http://stackexchange.com">Stack Exchange</a>
</div>
</div>
</div>
var editableDiv = document.getElementById("MyEditableDiv")
var editableDivImgs = editableDiv.getElementsByTagName("img")
for (var i = 0; i < editableDivImgs.length; i++) {
if(editableDivImgs[i].className != "safe")
{
editableDivImgs[i].parentNode.removeChild(editableDivImgs[i])
}
}
have you tried something like that?
Instead of removing all other elements extract all imgs and concatenate them into a new string:
var regex = /<img.*?>/gmi;
var imgsOnly = '';
var img;
while( ( img = regex.exec(str) ) !== null ) {
imgsOnly += img;
}
alert( imgsOnly );
精彩评论