Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery change inner text but preserve html

Tags:

jquery

I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

<a href="link.html">Some text <img src="image.jpg" /></a>  

replace "Some text" with "Other text", and the result should look like:

<a href="link.html">Other text <img src="image.jpg" /></a>  

EDIT: My current solution is following:

var aElem = $('a'); var children = aElem.children();  aElem.text("NEW TEXT"); aElem.append(children);  

But there must be some more elegant way of doing this.

like image 393
Drejc Avatar asked Mar 08 '11 13:03

Drejc


People also ask

Can I use innerHTML in jQuery?

All HTML elements have inner HTML properties. The . html() jQuery method retrieves the HTML content of the first element in the particular set of matched elements. Remember: jQuery innerHTML does not exist as a function.

How do I change the content of innerHTML of HTML elements?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.

How do I change the inner text of an element?

If you want to return or change just the text inside an element, use innerText. If you want to return or change just the text inside hidden elements, use textContent.


1 Answers

This seems to work just fine.

Live Demo

<html>     <head>     </head>     <body>         <a href="link.html">Some text <img src="img.jpg" /></a>     </body>      </html>     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>     <script type="text/javascript">         $(function(){             var $link = $('a');             var $img = $link.find('img');              $link.html('New Text');             $link.append($img);         });     </script> 
like image 187
Brandon Boone Avatar answered Sep 28 '22 04:09

Brandon Boone