greedsin
greedsin

Reputation: 1272

Change only text (Jquery)

I have a small problem that i cannot solve.I have this : <p>Text<span></span></p> and i want to change only the text of the <p>.Which means, when i click on an change-Button, the text based on an input field should replace the text. What i have tried is something like this : $("p").text("newText") but this will also remove the <span>.

So how can i only change the text and not the inner html...

Upvotes: 0

Views: 69

Answers (2)

Tom
Tom

Reputation: 7740

Put another span inside of the p tag and only change its contents:

<p>
  <span id="theText">Text</span>
  <span></span>
</p>

And then:

$('#theText').text('newText');

$('#theText').text('newText')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <span id="theText"></span>
  <span>some other span</span>
</p>

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30557

With your HTML above you can do

$('p').contents().first()[0].textContent='newText';

The idea is to take advantage of the fact that contents() includes text-nodes. Then, access by index [0] to get the native javascript DOM element and set the textContent

$('p').contents().first()[0].textContent = 'newText';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<p>Text<span>inside span</span>
</p>

Upvotes: 4

Related Questions