Ian Vink
Ian Vink

Reputation: 68810

jQuery - Bold all the words in a query

I have a large HTML document, a book, and need to bold every occurrence of "Toronto".

How is this done in jQuery?

Upvotes: 0

Views: 478

Answers (3)

manraj82
manraj82

Reputation: 6325

var bookPage = $("body");
bookPage.html(bookPage.html().replace(/Toronto/gi, '<strong>Toronto</strong>'));

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187262

var book = $('#theBook');
var lookFor = 'Toronto';
book.html(book.html().replace(lookFor, '<strong>'+ lookFor +'</strong>');

But how well this scales to the length of a super long book, I have no idea. But it should be fine for any reasonable amount of text shown on a single HTML page.

Upvotes: 1

Luca Matteis
Luca Matteis

Reputation: 29267

You should be doing this on the server side. Searching through an entire "book" and replacing occurrences of DOM objects with other DOM objects (bold elements) is quite memory unfriendly.

If the book is presented as a page structure, I suggest doing the replacement only at the current page, and running the same replacement once the page is changed.

Upvotes: 2

Related Questions