kamil
kamil

Reputation: 123

jQuery change child text

I have a jquery function that changes a text inside a element using a jquery "text" function. Inside this td element is child "a" tag like this.

<td class="v3"><a href="somelink">text to change</a>

The text to change is identified by the td class. When I change the text I lose the link. Question is how do I change the text using the parent element without touching the child (a href)?

Thanx

Upvotes: 12

Views: 34118

Answers (5)

solanki...
solanki...

Reputation: 5098

Working Code !!

using child-selector > with pseudo-class :first-child

const changeIt = () => {
  $('div.v3 > a:first-child').text('New Text');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="v3">
  <a href="somelink">text to change</a>
</div>

<button onclick="changeIt()">
  Click
</button>

Upvotes: 1

Vlad Nicula
Vlad Nicula

Reputation: 3696

If you have:

<td class="v3">
     <a href="somelink">text to change</a>
</td> 

Then in your function you should have something like this:

$("td.v3").children("a").text("new text");

However, this will select all links that are direct children of tds with class .v3. Adding a .first() after children should help:

$("td.v3").children("a").first().text("new text");

Upvotes: 19

CG_DEV
CG_DEV

Reputation: 818

If you want to change text in a select menu, you can do this by giving an option an id or class.

     $('selector').children('option[id=option_id]').text('new text');

Upvotes: 0

Tejs
Tejs

Reputation: 41236

You would simply change another element's text.

<td>
   <a href="#">Link</a>
   <span>SomeText</span>
</td>

Then invoke like so:

$('td').find('span').text('myNewText');

Upvotes: 2

Tim
Tim

Reputation: 6441

Wrap the text in a span element, and change the text in the span.

<div id="foo">
    <span>bar</span>
    <a href="#">link</a>
</div>

...

$('#foo span').text('new text');

Edit:

Or use $('td.v3 a').text("new text") to change the text in the anchor, if that's what you want to do.

Upvotes: 3

Related Questions