How do I replace a bit of text with string variable in javascript?

前端 未结 2 1679

I know this is a really simple question, but I need to replace this bit of text in a paragraph with a variable every time an even fires.

The markup looks like this

2条回答
  •  星月不相逢
    2021-01-28 23:18

    One example on how can be simple things made complicated :)

    javascript:

    // simple way:
    function replace_text(text) {
        var heading = document.getElementById('heading');
        heading.innerHTML = '

    ' + text + '

    '; } // complicated way: function replace_text2(text) { var heading = document.getElementById('heading'); var node = heading.childNodes[0]; while ( node && node.nodeType!=1 && node.tagName!='H1' ){ //console.log(node.nodeType,node); node = node.nextSibling; } if (node) { node.replaceChild(document.createTextNode(text),node.childNodes[0]); } }

    html:

    
    
    

    The script is here.

提交回复
热议问题