Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

On click change anchor text but not span

I am trying to change the text of an anchor (<a href=>) on clicking an element.

The html structure is:

<h1>
  <a href="">
      change this text
      <span class="breadcrumb">Do not change this text</span>
  </a> 
</h1>

Jquery:

var clickedtext = 'Different Text for A href';
$('h1 a').not('span.breadcrumb').text(clickedtext);

But for some reason it removes everything under <a href> and put that text.

Any help is highly appreciated.

Upvotes: 1

Views: 41

Answers (4)

FrenchTechLead
FrenchTechLead

Reputation: 1146

This is how to do it :

var clickedtext = 'Different Text for A href';
document.getElementById("toChange").innerText = clickedtext;
<h1>
  <a href="">
    <span id="toChange">change this text</span>
    <span class="breadcrumb">Do not change this text</span>
  </a>
</h1>

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can save that span element in variable and then change text of a and append span back.

var clickedtext = 'Different Text for A href. ';
var a = $("h1 a"), span = a.find('span')

a.click(function() {
  a.text(clickedtext).append(span)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="#">change this text. <span class="breadcrumb">Do not change this text</span></a> </h1>

Upvotes: 0

Neil
Neil

Reputation: 14313

If you use nodes, you can assign the text directly.

$("a").click(function (e) {
  e.preventDefault();
  $(this).contents().get(0).nodeValue = "new a href text"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><a href="">change this text<span class="breadcrumb">Do not change this text</span></a> </h1>

Upvotes: 3

Mazz
Mazz

Reputation: 1879

You could copy the element and append it later

var bread = $('h1 a').find('.breadcrumb').clone();
$('h1 a').text("cour text").append(bread);

Upvotes: 0

Related Questions