How to change a text with jQuery

Jquery

Jquery Problem Overview


I have an h1 with id of toptitle that is dynamically created, and I am not able to change the HTML. It will have a different title depends on a page. Now when it is Profile, I want to change it to New word with jQuery.

<h1 id="toptitle">Profile</h1> // Changing only when it is Profile  
// to
<h1 id="toptitle">New word</h1>

Note: If the text is Profile, then change it to New word.

Jquery Solutions


Solution 1 - Jquery

This should work fine (using .text():

$("#toptitle").text("New word");

Solution 2 - Jquery

Something like this should do the trick:

$(document).ready(function() {
    $('#toptitle').text(function(i, oldText) {
        return oldText === 'Profil' ? 'New word' : oldText;
    });
});

This only replaces the content when it is Profil. See text in the jQuery API.

Solution 3 - Jquery

Something like this should work

var text = $('#toptitle').text();
if (text == 'Profil'){
    $('#toptitle').text('New Word');
}

Solution 4 - Jquery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

Solution 5 - Jquery

Cleanest

Try this for a clean approach.

var $toptitle = $('#toptitle');

if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.  
  $toptitle.text('New Word');         

Solution 6 - Jquery

$('#toptitle').html('New world');

or

$('#toptitle').text('New world');

Solution 7 - Jquery

Pretty straight forward to do:

$(function() {
  $('#toptitle').html('New word');
});

The html function accepts html as well, but its straight forward for replacing text.

Solution 8 - Jquery

*In my case i have stored the new Value in the var altText

$('#toptitle').text(altText);

And it Worked

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshinView Question on Stackoverflow
Solution 1 - JqueryAndrew WhitakerView Answer on Stackoverflow
Solution 2 - JquerylonesomedayView Answer on Stackoverflow
Solution 3 - JqueryNicola PeluchettiView Answer on Stackoverflow
Solution 4 - JqueryNiklasView Answer on Stackoverflow
Solution 5 - JqueryJoshua PinterView Answer on Stackoverflow
Solution 6 - JqueryOHLÁLÁView Answer on Stackoverflow
Solution 7 - JqueryagmcleodView Answer on Stackoverflow
Solution 8 - JqueryAvinashView Answer on Stackoverflow