How to change sibling text of element without chan

2019-03-03 05:29发布

问题:

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.

回答1:

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.



回答2:

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')); 
   });


回答3:

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>



回答4:

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')); 
});

http://jsfiddle.net/hnfRe/402/



回答5:

use html instead of text function. . .

$('p').html($(this).html().replace('Login', 'Anmeldung'));


回答6:

<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')); 
});