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

前端 未结 2 1652

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 = '<h1>' + text + '</h1>';
    }
    
    // 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:

    <input type="button" onclick="replace_text('HELLO 1!');" value="Replace 1st text" />
    <input type="button" onclick="replace_text2('HELLO 2!');" value="Replace 2nd text" />
    

    The script is here.

    0 讨论(0)
  • 2021-01-28 23:25

    You could create a function that looks something like this.

    function replaceTitle (replaceText) {
        document.getElementById("heading").getElementsByTagName("h1")[0].innerHTML = replaceText;
    }
    

    If you are using jQuery it could look more like this.

    function replaceTitle (replaceText) {
        $("#heading h1").html(replaceText);
    }
    

    Then you call the function like this

    replaceText(yourVariable);
    

    It would probably be better to give your <h1> tag an id or a class so you can reference it directly, but I am going to assume that you have good reason for not doing so.

    0 讨论(0)
提交回复
热议问题