Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Example</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
  body {
    font-family: sans-serif;
  }
</style>
</head>
<body>
  <input type="button" id="theButton" value="Make it a link">
  <p id="example">This is <span></span> the example paragraph.</p>
</body>
</html>
 
jQuery(function($) {
  
  $("#theButton").click(function() {
    var targetWord, p, textNode, index, nodeWord, nodeAfter;
  
    // Our target word
    targetWord = "example";
    
    // Get the paragraph using jQuery; note that after we
    // use jQuery to get it (because it fixes getElementById for
    // us on older versions of IE), we then use [0] to access
    // the *raw* `p` element.
    // Then get the text node from it.
    p = $("#example").html();
    
 
    
    textNode = p;
    
    
    // Find our text in the text node
    index = textNode.indexOf(targetWord);
    
    alert(index);
    
    if (index !== -1) {
      // Split at the beginning of the text
      nodeWord = textNode.splitText(index);
    
      alert(textNode);
      
      // Split the new node again at the end of the word
      nodeAfter = nodeWord.splitText(targetWord.length);
      
      alert(nodeAfter);
      
      // Insert a new anchor in front of the word
      anchor = document.createElement('a');
      anchor.href = "http://stackoverflow.com";
      p.insertBefore(anchor, nodeWord);
      
      // Now move the word *into* the anchor
      anchor.appendChild(nodeWord);
      
    }
  });
  
});
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers