Results 1 to 2 of 2

Thread: replace a peace of text?

  1. #1
    Join Date
    Dec 2006
    Posts
    74
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default replace a peace of text?

    i have a huch at how this might be possible (innerHTML tag) but basically i would like a bit of help in making a script that:
    1. Will get a div by id
    2. Will look through that div and find a certain peace of text
    3. will replace that peace of text with a peace of html (eg: <span id="">test</span>)


    all help much appreciated

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Sure you don't want to replace it with a war of text?

    innerHTML is indeed the easiest way, but not the best. Try:
    Code:
    function surroundText(inEl, text, withEl) {
      var nv;
      for(var i = 0, e = inEl.childNodes; i < e.length; ++i)
        if(e[i].nodeType === 3) {
          if((nv = e[i].nodeValue).indexOf(text) !== -1) {
            var tels = [
              nv.substr(nv.indexOf(text) + text.length),
              text,
              nv.substr(0, nv.indexOf(text))
            ];
            for(var j = 0; j < tels.length; ++j)
              inEl.insertBefore(e[i], document.createTextNode(tels[j]));
            inEl.parentNode.removeChild(inEl);
            return true;
          }
        } else
          if(surroundText(e[i], text, withEl))
            return true;
      return false;
    }
    Untested.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •