Reputation: 10228
I have a textarea which my website's users enter their own content in it (based on markdown standards) and then publish it in my website.
The library I use (which converts markdown to HTML per keydown
) produces tags without attributes. So to keep safe the UI against what the user enters, I have this code:
function cleanHtml(html) {
var $doc = $('<span>' + html + '</span>');
$('*', $doc).each(function (index, el) {
if (el.hasAttributes('attributes')) {
while ($(el).contents().length) {
$(el).contents().last().insertAfter(el);
}
$(el).remove();
}
});
return $doc.html();
}
The Code above removes every tag which has at least one attribute. This works fine.
Recently I figured out the markdown-converter-library also produces some tags which have either the href attribute or both src
and alt
attributes. Something like these:
<a href="../path">my link</a>
<img src="../path" alt="something" />
Now I need to edit cleanHtml()
function to remove every tag which has attributes except the two examples above.
How can I do that?
Upvotes: 0
Views: 46
Reputation: 11297
Check if $(el).attr('src')
or $(el).attr('src')
return undefined:
el.hasAttributes('attributes') && ( !$(el).attr('src') && !$(el).attr('href') )
$('*').each(function(i, el){
if(el.hasAttributes('attributes') && ( !$(el).attr('src') && !$(el).attr('href') ) ) {
$(el).remove();
}
});
p {
width:100px;
height:100px;
background:#ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a href="http://unsplash.it" style="color:#f44336">my link</a>
<a href="http://unsplash.it" style="color:#f44336;size:16px">Unsplash 2</a>
<img src="http://unsplash.it/100" alt="something" />
<p id="s" data-a="a"></p>
Upvotes: 1