Hastig Zusammenstellen Hastig Zusammenstellen - 1 month ago 5x
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, ''));

.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>

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


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



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.



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 = "";

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>

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