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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…