jQuery - how to change text after element "i"?

6

Follow the code below:

<div class="file-caption-name">
    <i class="glyphicon glyphicon-file kv-caption-icon"></i>
    Alterar texto aqui
</div>

I've tried it this way:

$('div.file-caption-name i').text('your new title');

The result looks like this:

<div class="file-caption-name">
    <i class="glyphicon glyphicon-file kv-caption-icon">your new title</i>
    Alterar texto aqui
</div>
    
asked by anonymous 04.10.2017 / 18:11

2 answers

7

To change the text after and not the whole text of .file-caption-name. you can do in two ways, add an inline element span:

$(document).on("click", "#trocar", function () {
    $(".file-caption-name > span").text("Olá, mundo!");
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="file-caption-name">
    <i class="glyphicon glyphicon-file kv-caption-icon"></i>
    <span>Alterar texto aqui</span>
</div>

<button id="trocar">Trocar</button>

Or you can get <i> and detach using detach() and then remove the content and re-add the <i> :

$(document).on("click", "#trocar", function () {
    var icon = $(".file-caption-name i").detach();
    $(".file-caption-name").text("Foo, Bar!");
    icon.prependTo(".file-caption-name");
});
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="file-caption-name">
    <i class="glyphicon glyphicon-file kv-caption-icon"></i>
    Alterar texto aqui
</div>

<button id="trocar">Trocar</button>
    
04.10.2017 / 18:35
6

UPDATED ANSWER

You can do a treatment to just get the TEXT inside the% with% with% with% and make a% with% with% with% eliminating whitespace before and after text with div :

 $('div.file-caption-name').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace($.trim($('div.file-caption-name').text()),'your new title');
});

$('div.file-caption-name').contents().filter(function() {
    return this.nodeType == 3
}).each(function(){
    this.textContent = this.textContent.replace($.trim($('div.file-caption-name').text()),'your new title');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="file-caption-name">
    <i class="glyphicon glyphicon-file kv-caption-icon"></i>
    Alterar texto aqui
</div>
    
04.10.2017 / 18:14