Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
JQuery change inner text but preserve html

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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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>
over 4 years ago · Santiago Trujillo Report

0

Since you can't modify the link an option would be to simply use replace

$("a").html($("a").html().replace("Some text", "Other text"));

Example on jsfiddle.

over 4 years ago · Santiago Trujillo Report

0

Wrap the text you want to change in a span

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

$('a span').html( 'new text' );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!