Question

We are supplying a blob of HTML content to be imported and displayed on someone else's page. The owners of the page put a title around our content blob, but the title is the name of our web service that provides the content, rather than a user-friendly name that we want to display to users. They can't figure out how to change the title on their end, we don't want to change the name of our web service, and it needs to look good for a demo in a few days.

The ideal solution would be for them to figure out how to use their portal tool to be able to customize titles, but that is not likely to happen before the demo. So I was thinking we could include some JavaScript in the content that we send them, which would change the title for them. This would buy them time to figure out what they are doing.

The code for their title looks like this:

<div class="titleClass"> Bad Title </div>

I would like to replace "Bad Title" with "Good Title". I would like to locate this text on the page using a jQuery selector, but unfortunately there are multiple div items with the class of titleClass and I only want to change one of them.... is there a selector I could use that would also check for the text "Bad Title" inside the div tag? Or do I have to write a separate function that would loop through all the different titles on the page, and test each one to see if it contains "Bad Title"? If I have to do the second, does anyone have sample code to share?

Was it helpful?

Solution

Maybe You want do it simplier?

$(document).ready( function() {
  $('div.titleClass:contains("Bad Title")').text( "Good title" );
});  

Look at the contains selector.

OTHER TIPS

First get a collection of all the elements with matching text:

var $matches = $('div.titleClass').filter(function() {
    return $(this).text() == 'Bad Title';
});

and then replace the text of the matching elements:

$matches.each(function() {
    $(this).text('New Title');
});

The above will look for elements with text exactly matching 'Bad Title'. If you want any element that contains the text 'Bad Title', e.g. 'A Bad Title', you should use indexOf or search, e.g.:

return $(this).text().indexOf('Bad Title') > -1;

One last caveat is case-sensitivity. If you want to do a case-insensitive match, I would suggest something like this:

// the div contains Bad Title of whatever case
return $(this).text().search(/Bad Title/i) > -1;

// the div exactly matches Bad Title of whatever case
return $(this).text().search(/Bad Title/i) > == 0;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top