问题
my question was pretty much explained up in the title. How do I get HTML tags inside of a Javascript Text Node? The result of my code on the page is...
<a href="http://www.example.com">Click Here</a>
However, I want "Click Here" to be a link. I am new to Javascript, so this would help me out a lot. Below is an example of what I'm talking about...
<div id="mydiv">
</div>
<script type="text/javascript">
var mynode=document.createTextNode('<a href="http://www.example.com">Click Here</a>');
document.getElementById('mydiv').appendChild(mynode);
</script>
回答1:
You can't put links in a text node. Links are elements. Elements can (sometimes) contain text nodes, but the reverse is not true.
You need to create an element, set attributes on it, then append text to that element.
var link = document.createElement('a');
link.setAttribute('href', 'http://www.example.com');
link.appendChild(document.createTextNode('Click Here'));
document.getElementById('mydiv').appendChild(link);
回答2:
<div id="mydiv">
</div>
<script type="text/javascript">
var element = document.createElement('a');
element.setAttribute("href","http://www.example.com");
element.appendChild(document.createTextNode('Click Here'));
document.getElementById('mydiv').appendChild(element); </script>
</script>
回答3:
You're looking for document.createElement
, not document.createTextNode
. Text-nodes cannot contain HTML.
An easy alternative, if you're not using complex Javascript (which it seems you aren't) would just be:
document.getElementById('mydiv').innerHTML.='<a href="http://www.example.com">Click Here</a>';
回答4:
I needed to insert an element in the middle of a text node (replace a word with a span). I did it by replacing the text node altogether:
(uses jQuery)
function replace_text(element, search, replacement_html){
if(!element) element=document.body;
var nodes=element.childNodes;
for(var n=0;n<nodes.length;n++){
if(nodes[n].nodeType==Node.TEXT_NODE){
if(nodes[n].textContent.match(new RegExp(that.escapeRegExp(search),'gi'))){
var newtextContent=nodes[n].textContent.replace(
new RegExp(escape_regex(search),'gi'), replacement_html);
$(nodes[n]).before(newtextContent).remove();
}
} else {
replace_text(nodes[n], search, replacement_html);
}
}
}
function escape_regex(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
And then calling:
$('.highlight_terms_here').each(function(){
replace_text(this,
the_word,
'<span style="background-color: yellow">'+the_word+'</span>');
})
Or simply:
replace_text($('#contents')[0], the_word,
'<span style="background-color: yellow">'+the_word+'</span>');
来源:https://stackoverflow.com/questions/10888198/how-do-i-get-html-tags-inside-of-a-javascript-text-node