Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change child text

Tags:

jquery

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

like image 286
kamil Avatar asked Sep 14 '11 11:09

kamil


People also ask

How do I toggle text in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

How to use children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


2 Answers

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");
like image 90
Vlad Nicula Avatar answered Oct 10 '22 04:10

Vlad Nicula


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.

like image 27
Tim Avatar answered Oct 10 '22 06:10

Tim