user3532637 user3532637 - 2 months ago 6
Javascript Question

How to change sibling text of element without changing html using jQuery?

I'm trying to replace text only, but without touching any other tags.

<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>


$('p').each(function() {
$(this).text($(this).text.replace('Login', 'Anmeldung'));
});


Bad result:

<p>
Anmeldung
</p>


Result as I would like it to be:

<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Anmeldung
</a>
</p>


How can I do this? This is only a sample, deeper structure of
p
tags can be completely different.

Answer

Use .html() instead of .text()
This preserves your html tags

$('p').each(function() {
    $(this).html($(this).html().replace('Login', 'Anmeldung')); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    <a href="login.php">
        <i class="fa fa-sign-in"></i> 
        Login
    </a>
</p>

Fiddle using your example.

Comments