Change text that appears before span

Asked

Viewed 614 times

0

I want to change a text that appears before a span with Jquery, this text will be changed when some user renames a folder.

<li>
  <a href="#">
     Pasta 1
     <span class="tag tag-pill tag-danger" id="spanPasta1">0</span>
  </a>
</li>

When I change using the code below, the span is deleted.

$("#spanPasta1").closest('a').text('pasta 2')

I want to change the text without having to change all the CSS code and take the span out of the href.

1 answer

2


You can use the method contents() which returns only the text nodes. As the text is the first node of <a>, you use first().

Example:

$("#spanPasta1")
.closest("a")
.contents()
.first()[0]
.textContent = "pasta 2";
/* apenas para ilustrar*/
span{
   display: block;
   background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <a href="#">
     Pasta 1
     <span class="tag tag-pill tag-danger" id="spanPasta1">0</span>
  </a>
</li>


Another way is by using detach():

var span = $("#spanPasta1"), // seleciono o SPAN
    span_a = span.closest("a"); // seleciono o A
    
span = span.detach(); // retiro o SPAN e "reservo"

span_a
.text('pasta 2')
.append(span); // altero o texto do A e reintroduzo o SPAN no A
/* apenas para ilustrar*/
span{
   display: block;
   background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
  <a href="#">
     Pasta 1
     <span class="tag tag-pill tag-danger" id="spanPasta1">0</span>
  </a>
</li>

  • 1

    These two examples I didn’t know, I was trying to find a solution.

  • The solution $("#spanPasta1"). Closest("a"). Contents(). first()[0]. textContent = "folder 2"; functioned perfectly :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.