1

I'm having trouble getting this to work...it just replaces the entire page with the result

var str="textiwanttoreplace";
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?

kevin
  • 13
  • 4

3 Answers3

2

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

Sarfraz
  • 355,543
  • 70
  • 511
  • 562
  • changed to that, but I can't seem to get it to work. Am I missing something?(new code in the question) – kevin Jul 29 '10 at 19:33
1

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.

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
  • no only once, how would I do that? I'm more or less a total noob when it comes to javascript – kevin Jul 29 '10 at 19:34
0

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>
ryan
  • 6,353
  • 5
  • 39
  • 66