webmonkey237 webmonkey237 - 1 year ago 39
jQuery Question

jQuery: changing a string of HTML before it displays

I am working on a front end script that copies and then outputs the HTML as plain text, I have got that part working in my Fiddle below.


My question, is there a way I can change the output string before it displays e.g. in my Fiddle example change the word "test" to "boat" and change the URL "http://www.linkedin.com" to "http://www.google.com" just as an example.

$('.output').click(function () {
$('.outputCon').css('display', 'block');
var $code = $('.redCon').html();

I have been looking at a few string replacement code options:

$('.outputCon').html($($code).html().replace('test', 'dog'));

Which I am not sure if I have done correctly as I am not sure how to implement this to change the string before the HTML has been displayed, sorry my explanation is hard to follow, ill happily answer any questions.

Answer Source

Your variable $code already contains the html text so you can use the replace method on that. Instead of:

$('.outputCon').html($($code).html().replace('test', 'dog'));

you can just do this:


Also, it seems like you're mixing up PHP with jQuery; you don't need to use $ for variables in jQuery.