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.
Wrap text you want to replace in a span or something.
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
<span class="replace-login">Login</span>
</a>
</p>
and js
$('.replace-login').each(function() {
$(this).text($(this).text.replace('Login', 'Anmeldung'));
});
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.
If you want to change all text sibling of i
, select i
tag in p
and use Node.nextSibling
property to selecting sibling text after element and change it.
$("p > a > i")[0].nextSibling.nodeValue = "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>
But if you want to replace part of text, use this code
$("p > a").html(function(i, html){ return 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>
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>
$('p').each(function() {
$(this).find("a").text($(this).find("a").text.replace('Login', 'Anmeldung'));
});
You can try this DEMO LINK HERE
<p>
<a href="login.php">
<i class="fa fa-sign-in"></i>
Login
</a>
</p>
JS..
$('p').each(function() {
$(this).html($(this).html().replace('Login', 'Anmeldung'));
});
use html instead of text function. . .
$('p').html($(this).html().replace('Login', 'Anmeldung'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.