i am using jquery replaceText plugin. with this plugin i can successfully replace text of an element like this:
<div>some text to be replaced here.</div>
<script type="text/javascript">
$(function(){
$("div").replaceText("some text to be replaced here", "a new text for replacement");
})
</script>
however when that div becomes something like this:
<div>some text to be <a href="somelink">replaced</a> here.</div>
the replacement is not working.
how should i proceed here?
2 Answers 2
So you want to replace a subset of text with another subset of text and you want to work across nodes.
Looks like you want a Range.
So you just have to make a new Range using document.createRange(). Make it point to where you content starts.
So just find the start node and the start offset somehow then call range.setStart(node, offset). I would presume the node will be your container and the offset is just calculated.
Then call range.extractContents() to remove the original text from the DOM.
Then just range.insertNode(textNode) to insert the next text into the DOM.
1 Comment
When operating on the HTML of the page, all the tags are in the HTML stream so you can't just do a direct replacement of only the text without allowing for intervening tags.
It isn't matching "some text to be replaced here" because that string of text doesn't exist as a single string of text in this HTML:
div>some text to be <a href="somelink">replaced</a> here.</div>
You would have to replace individual pieces of text that actually exist as individual streams of text like "some text to be " and "replaced".
<a>element just disappear leaving the<div>with just the new text as plain text?<a>element to stay as otherwise is breaking the page. however i also would like to know how it would be if it just disappeared.<a>, but what will be its content after the replace operation? How would you decide which word(s) from the replacement text end up inside the<a>and which end up outside?