Replace specific text in the document with javascript?
I'm having trouble getting this to work...it just replaces the entire page with the result
var str="textiwan开发者_运维百科ttoreplace";
var el = document.getElementById('welcome');
el.innerHTML = str;
var date = new Date();
var hours = date.getHours();
if (hours >= 8 && hours < 13) {
el.innerHTML = str.replace("textiwanttoreplace", "It's 8 and 13");
} else if (hours >= 13 && hours < 18) {
el.innerHTML = str.replace("textiwanttoreplace", "It's 13 and 18");
} else if (hours > 18 && hours <= 23) {
el.innerHTML = str.replace("textiwanttoreplace", "It's 18 and 23");
} else {
el.innerHTML = str.replace("textiwanttoreplace", "Hello");
}
edit: changed, and now I'm not seeing any results am I missing something?
It would, if you want to replace that text and put at certain part of the page, you should go about something like this:
var str="textiwanttoreplace";
var el = document.getElementById('element_id');
el.innerHTML = str;
So instead of:
document.write();
Use:
var el = document.getElementById('element_id');
el.innerHTML = str.replace("textiwanttoreplace", "Good Morning");
Just replace element_id
with the id of the element in which you want to put the result of the text.
Update:
Based on your comment, I tested it and it works, you can check it out here:
http://jsbin.com/odipu3
document.write
is BAD practice.
Does the text (that you want to replace) exist in multiple locations in your document? The right way to do this text replacement is to traverse the DOM and replace the text content of the specific element(s) that contain said text.
You'll want to narrow down the parent of the text you're to replace. You could do it against the entire document, but it will be extremely inefficient.
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript></script>
<script type="text/javascript">
$(document).ready(function() {
$("div.replace-me").text($(this).text().replace('will replace', 'Good morning'));
});
</script>
精彩评论