L84
L84

Reputation: 46308

Change Text using jQuery

I have a script that is pulling in news from Yahoo on a certain subject. It renders the title of the news feed like this:

<div class="header-title">subject - Yahoo! News Search Results</div>

I would like to change this to read differently. Since this is inserted via JS I thought I could change this with jQuery.

I attempted this:

$('.header-title').text('Subject News');

that did not work, I then attempted this:

$('.header-title').empty();
$('.header-title').text('Subject News');

that also did not work.

Both of the above methods look as if they had no effect on the text.

I am not sure what to do to remove the old text and replace with my text.

Note: All of my code is inside jQuery's Document Ready IE:

$(function(){ 
   //Code Here 
});    

Upvotes: 1

Views: 1478

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

What's probably happening:

  1. First you're setting the text: $('.header-title').text('Subject News');
  2. THEN ... after the data finishes the load of the Yahoo or whatever content your text gets replaced actually with the new fetched data

    Change the text inside the load callback (after data is loaded) and it will work.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

This solution assumes you have no access to the other script that creates the feed widget

WIthout knowing more about other script it sounds like it is asynchronous, and creates the title elements also. You could have a timed interval loop that checks for the element to exist and once it exists do the update:

function changeYahooTitle(){
     var $yhooTitle=$('.header-title');
    if($yhooTitle.length){
        $yhooTitle.text('My New Title');
    }else{
        /* doesn't exist so check again in 1/10th second, will loop recursively until found*/
        setTimeout(changeYahooTitle, 100);
    }
}

Then on page load:

$(function(){
  changeYahooTitle()

})

If you do have access to the other script it can be modified to accommodate your needs, or you can still use this solution

Upvotes: 1

jonasnas
jonasnas

Reputation: 3570

It doesn't work because you call the function before the element is created. If you put your function inside <script> tag after the <div> element it should work

Upvotes: -1

Lil&#39; Bits
Lil&#39; Bits

Reputation: 898

Try using html() instead of empty() and text()

$(document).ready(function(){
    $(".header-title").html("Subject News");
});

Upvotes: 0

VisioN
VisioN

Reputation: 145368

Don't forget to put your code in DOM ready:

$(function() {
    $(".header-title").text("Subject News");
});

Otherwise the code should work fine.

Upvotes: 3

Related Questions