Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda