在javascript中更改生成的代码中的文本字符串

时间:2018-02-21 16:03:56

标签: javascript html

我在网站上有一个结帐页面,用于生成送货讯息。我需要更改该送货信息的文本。

以下是需要更改的元素的路径:

#order_review > table > tfoot > tr.shipping > td > p

这是我想采取的方法(如果是更好的方法,请纠正我),但我需要帮助深入到正确的元素:

var oldstring = "Enter your shipping information above to show shipping options."
var changeit = document.getElementById("order_review");
changeit.oldstring.replace("Enter your shipping information above to show shipping options.", "Enter your full address to verify free delivery.");

3 个答案:

答案 0 :(得分:1)

var qs = document.getElementById("order_review");
qs.querySelector("table > tfoot > tr.shipping > td > p").innerHTML = "Enter your full address to verify free delivery.";
<div id="order_review">
  <table>
    <tfoot>
      <tr class="shipping">
        <td>
          <p>Enter your shipping information above to show shipping options.</p>
        </td>
      </tr>
    </tfoot>
  </table>
</div>

答案 1 :(得分:1)

我喜欢在更新DOM上的文字时使用textContent

let el = document.querySelector("#order_review > table > tfoot > tr.shipping > td > p");
el.textContent = "Enter your full address to verify free delivery.";

答案 2 :(得分:1)

您可以使用querySelector方法作为评论中提到的Andereas。您不需要使用replace,只需将新文本分配到innerHTMLtextContent

var changeit = document.querySelector("#order_review > table > tfoot > tr.shipping > td > p");
changeit.textContent = "Enter your full address to verify free delivery.";

如果你想保留对order_review的引用并从那里向下钻取,你可以这样做:

var changeit = document.getElementById("order_review");
changeit.querySelector("table > tfoot > tr.shipping > td > p").textContent = "Enter your full address to verify free delivery.";