Using Javascript To Insert Links In Text Without Replacing Entire Content Of Div
Solution 1:
My questions is, is there a way to replace JUST the keywords with
<a href='link.html'>keyword</a>
, WITHOUT replacing the entire content of the div?
Yes. It's one of the (few) places where jQuery doesn't really offer you much.
Down at the raw DOM API level, though, the Text
node containing the actual text of the element has a splitText
function with which you can split the node into two adjacent nodes at a specific location. So in your case, you'd split at the beginning of the word and then again after the end of it, then wrap that middle Text
node in a new anchor.
Here's an example: Live copy | source
HTML:
<input type="button"id="theButton" value="Make it a link">
<p id="example">This is the example paragraph.</p>
JavaScript:
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")[0];
textNode = p.firstChild;
// Find our text in the text node
index = textNode.nodeValue.indexOf(targetWord);
if (index !== -1) {
// Split at the beginning of the text
nodeWord = textNode.splitText(index);
// Split the new node again at the end of the word
nodeAfter = nodeWord.splitText(targetWord.length);
// 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);
}
});
});
Naturally there are some things you'd want to do to improve that:
- Handle the
index === 0
case without creating an empty text node at the beginning of the parent element. (Harmless, but less than ideal.) - Handle the case where the word is at the very end of the parent, so you don't end up with an empty text node there. (Again.)
Solution 2:
you can replace only keywords without replacing all content like this,
functionkeywordconvert(str, p1, offset, s) {
return"<a href=\"link?t="+encodeURIComponent(p1)+"\">"+p1+"</a>";
}
functionsearch(keyword) {
var content = document.getElementById("content");
var re = newRegExp("("+keyword+")","g");
content.innerHTML = content.innerHTML.replace(re, keywordconvert);
}
USAGE
search("keyword");
Solution 3:
Yes, but you would have to loop through all text nodes manually.
Far easier would be to strip <script>
tags first, because once they have been run they are not needed on the page (everything is kept in memory).
$('#content script').remove();
That will remove the scripts from the #content
element, then you can run your existing replace code without problems.
Post a Comment for "Using Javascript To Insert Links In Text Without Replacing Entire Content Of Div"