santa
santa

Reputation: 12512

Remove span using jQuery

I have a dynamic loop that generates the output similar to the following snippet. I need to remove <span><i> and <br> and just leave the text wrapped in link. I've tried the following:

$('#links a').each(function(){
    var this = $(this),
    span = this.find('span'),
    text = span.text();

    span.remove();
    this.append(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="links">
  <a href="/1">
    <span class="inline">
      <i class="fa fa-question"></i>
      <br>Help
    </span>
  </a>

  <a href="/2">
    <span class="inline">
      <i class="fa fa-gear"></i>
      <br>Fix
    </span>
  </a>
</div>

Not getting expected results. What am I missing?

Upvotes: 3

Views: 3483

Answers (2)

Shiladitya
Shiladitya

Reputation: 12181

Here you go with a solution

$('#links a').each(function(){
    var text = $(this).text();
    $(this)
      .empty()
      .append(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="links">
  <a href="/1">
    <span class="inline">
      <i class="fa fa-question"></i>
      <br>Help
    </span>
  </a>

  <a href="/2">
    <span class="inline">
      <i class="fa fa-gear"></i>
      <br>Fix
    </span>
  </a>
</div>

First get the text into a variable and then remove the child elements using empty method & at the last append the text.

Upvotes: 1

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

this is a reserved keyword in JS. You need to change this to something else:

$('#links a').each(function(){
    var $this = $(this),
    span = $this.find('span'),
    text = span.text();

    span.remove();
    $this.append(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="links">
  <a href="/1">
    <span class="inline">
      <i class="fa fa-question"></i>
      <br>Help
    </span>
  </a>

  <a href="/2">
    <span class="inline">
      <i class="fa fa-gear"></i>
      <br>Fix
    </span>
  </a>
</div>

Upvotes: 2

Related Questions