Hastig Zusammenstellen Hastig Zusammenstellen - 3 months ago 8
Javascript Question

Need help to identify why removing element and its contents in jQuery is not working

Can anybody tell me what I'm doing wrong with this jQuery code here?



$('.deleter').click(function() {
var toDelete = $(this).attr('stringStorage');
$('.urls').text($('.urls').text().replace(toDelete, ''));
$(this).remove();
});

.deleter {
display: inline-block;
margin-right: 10px;
background-color: red;
color: white;
cursor: pointer;
}
.deleter:hover { background-color: orange; }

br { line-height: 22px; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="urls">
<span class="deleter" stringStorage="www.firsturl.com">x</span>www.firsturl.com<br>
<span class="deleter" stringStorage="www.anothereurl.com">x</span>www.anothereurl.com<br>
<span class="deleter" stringStorage="www.athirdurl.com">x</span>www.athirdurl.com<br>
</div>





It works fine at removing the '.deleter' element..

https://jsfiddle.net/Hastig/ku0t7mey/5/

But once
$('.urls').text($('.urls').text().replace(toDelete, ''));
in the element .deleter is removed but the contents (x) are left behind.

https://jsfiddle.net/Hastig/ku0t7mey/4/

UPDATE

I can get the whole function to work with this gents solution here.. http://stackoverflow.com/a/19318945/3377049

But I will leave this question open for anyone who can answer why the code I used seems to remove all html elements within the targeted element.

https://jsfiddle.net/Hastig/ku0t7mey/6/

Answer

You can use .nextSibling, .textContent to set #text node adjacent to clicked .deleter element to empty string "".

$('.deleter').click(function(e) {
    var toDelete = $(this).data('stringStorage');
    this.nextSibling.textContent = "";
    $(this).remove();
});

You can also substitute using data-* attribute for custom attribute at html

<div class="urls">
  <span class="deleter" data-string-storage="www.firsturl.com">x</span>www.firsturl.com<br>
  <span class="deleter" data-string-storage="www.anothereurl.com">x</span>www.anothereurl.com<br>
  <span class="deleter" data-string-storage="www.athirdurl.com">x</span>www.athirdurl.com<br>
</div>

jsfiddle https://jsfiddle.net/ku0t7mey/8/

you could alternatively use .contents(), .filter(), .trim(), .add() to remove the #text node at same call wherethisis removed fromdocument`

  $(".urls").contents().filter(function() {
    return this.nodeType === 3 && this.nodeValue.trim() === toDelete
  }).add(this).remove();

https://jsfiddle.net/ku0t7mey/12/