Reputation: 115
I have some textarea with a content inside contain img & div. I need to remove the all img and div. but keep the alt of the img.
In snippet below it's remove all img and div.
$('textarea').val(function(i, val) {
return $('<div>').html(val).text();
});
textarea {
width: 250px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="mycontent">
<textarea>some img
<img src='whatever1.gif' alt='Title 1'>in text area
<img src='whatever2.gif' alt='Title 2'>must be gone but keep img alt.
<img src='whatever3.gif' alt='Title 3'>all div must gone.
<div id="someID fromdiv">
<div></div>
</div>
</textarea>
</div>
<div class="mycontent">
<textarea>ANOTHER some img
<img src='whatever4.gif' alt='Other Title 4'>in text area
<img src='whatever5.gif' alt='Title 5'>must be gone but keep img alt.
<img src='whatever6.gif' alt='Other Title'>all div must gone.
<div id="someID" class="classDiv">
<div></div>
</div>
</textarea>
</div>
What the best way to keep the alt of the img not also be removed?
Any guide really appreciate.
Thank you.
Upvotes: 1
Views: 711
Reputation: 21881
Replace the images with their alt
attribute before removing the included HTML.
$('textarea').val(function (i, val) {
return $('<div>').html(val)
// replace images with their alt attribute
.find("img").replaceWith(function() {
return this.alt;
}).end()
.text();
});
$('textarea').val(function (i, val) {
return $('<div>').html(val)
// replace images with their alt attribute
.find("img").replaceWith(function() {
return this.alt;
}).end()
// remove any html
.text();
});
textarea {
width: 500px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="mycontent">
<textarea>some img
<img src='whatever1.gif' alt='Title 1' />in text area
<img src='whatever2.gif' alt='Title 2' />must be gone but keep img alt.
<img src='whatever3.gif' />all div must gone.
<div id="someID fromdiv">
<div></div>
</div>
</textarea>
</div>
<div class="mycontent">
<textarea>ANOTHER some img
<img src='whatever4.gif' alt='Other Title 4' />in text area
<img src='whatever5.gif' alt='Title 5' />must be gone but keep img alt.
<img src='whatever6.gif' alt='Other Title' />all div must gone.
<div id="someID" class="classDiv">
<div></div>
</div>
</textarea>
</div>
Upvotes: 1
Reputation: 849
the following code help you, but i am not understand why you written html in text area its not valid html code
<script type="text/javascript">
function RemoveAllImge() {
$("#YourTextAreaID img").each(function () {
$(this).attr('src', '');
});
};
function RemoveAllDiv() {
$("#YourTextAreaID div").each(function () {
$(this).remove();
});
};
</script>
Upvotes: 0