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

前端 未结 2 1682

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: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

    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.

提交回复
热议问题