Quick JavaScript help?

Discussion in 'Web Design and Development' started by AWShuttleworth, Nov 3, 2010.

  1. AWShuttleworth
    Expand Collapse
    macrumors newbie

    Jul 1, 2007
    I'm trying to use JS to check if a string is on a page, and if it is, to inject some HTML into a DIV on the page. Here's my code—what stupid mistake am I making?

    <script type="text/javascript">
      if (document.body.innerHTML.indexOf('My String'))
      	document.getElementById('target').innerHTML = 'Hello, world!';
    <div id="target"></div>
  2. Dunmail
    Expand Collapse
    macrumors regular

    Mar 27, 2009
    Skipton, UK
    Where are you running this script? It is only likely to work if you run it after the body has loaded so either attach it using the body onload event or if you are using jquery or the like use document.ready.

Share This Page