Change text that appears before span

0

I want to change text that appears before a span with JQuery, this text will change when a 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 from within the href.

    
asked by anonymous 27.03.2018 / 08:12

1 answer

2

You can use the contents() method that returns only the text nodes. Since 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><ahref="#">
     Pasta 1
     <span class="tag tag-pill tag-danger" id="spanPasta1">0</span>
  </a>
</li>

Another way is to use 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><ahref="#">
     Pasta 1
     <span class="tag tag-pill tag-danger" id="spanPasta1">0</span>
  </a>
</li>
    
27.03.2018 / 09:59