Tân
Tân

Reputation: 1

Change .text() content and keep child html

Can you tell me how to remove character @ from this span tag without changing all child html(s)?

$('button').click(function() {
  // ...
});
#name {
  background-color: #ccc
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>
  <span id="name">
    <a href="#">Harry</a>
  </span> 
  
  says: Hello @<span id="name">
    <a href="#">Hermione</a>
  </span>
</span><br />

<button>Remove</button>

My idea: get the parent .text(), split character @, override parent text (parent.text('')) and append 2 parts to the parent. But this way has a big problem: all child html(s) wouldn't be kept.

Upvotes: 1

Views: 110

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337733

Firstly you should change the duplicate id attributes to classes, or remove them entirely.

To solve your actual issue you can loop through the nodes held within the top level span and remove any @ characters which appear in any textNode values. Try this:

$('button').click(function() {
  $('body > span').contents().each(function() {
    if (this.nodeType == 3) {
      this.nodeValue = this.nodeValue.replace('@', '');
    }
  });
});
#name {
  background-color: #ccc
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>
  <span class="name">
    <a href="#">Harry</a>
  </span> says: Hello @<span class="name">
    <a href="#">Hermione</a>
  </span>
</span>
<br />

<button>Remove</button>

Upvotes: 2

Chris Lear
Chris Lear

Reputation: 6752

I've added an id to the outer <span> and deduplicated your name ids.

$('button').click(function () {

  $('#outer').html($('#outer').html().replace(/@/,''));
  
});
#name {
  background-color: #ccc
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='outer'><span id="name"><a href="#">Harry</a></span> says: Hello @<span id="name2"><a href="#">Hermione</a></span></span>

<br />

<button>Remove</button>

Upvotes: 2

Related Questions