Bix Bix - 5 months ago 40
jQuery Question

Script replacing value from variables into document

I would like to undertake following action: Get values from text inputs, then check if first of them occurs in whole document. If it occurs in the document I would like to replace all instances of it by value of second variable.

Code in snipet is not correct cause function replace doesn't work...
Has anyone idea how to resolve it?

Thank you in advance!

var replaced = $('#replaced').val();
var modified = $('#modified').val();

if($( ".entireSite:contains(" + replaced + ")" ).text() === '') {
alert('there is no wanted word/phrase at the website');
} else {
$('.entireSite').text().replace(replaced, modified);

<script src=""></script>
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<input type="text" id="replaced" value="word/phrase to modify"><br><br>
<input type="text" id="modified" value="new word/phrase"><br><br>
<input type="submit" value="submit" id="submit">

<div class="entireSite">
<p>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas sed sollicitudin
lectus. Sed libero tellus, sodales quis eros
eu, vestibulum interdum nibh. Nunc Lorem quis
diam vitae enim finibus pretium ut a ipsum.
Cras ut ullamcorper mi, vel fringilla augue.
Pellentesque Lorem consequat vulputate ipsum
sit amet faucibus. Aliquam erat orci, cursus
id tempor bibendum, condimentum vitae enim.</p>

Answer Source

This is happening because you are only setting the variables "replaced" and "modified" when the document is loaded, not when you click on the button. This is an explanation to @Phani Kumar M's answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download