无法使用javascript更改outerHTML

时间:2016-05-12 14:47:19

标签: javascript replace outerhtml

我在页面上有这个HTML模板:

<div id="bid_wrapper_[[bid_id]]_[[template]]">
    <div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
        <div id="bid_delete_[[bid_id]]_[[template]]"><img src="/images/icons/cross.png"></div>
        <div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
        <div><input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]"></div>
        <div><input name="bid_price" id="bid_price_[[bid_id]]_[[template]]"></div>
    </div>
</div>

我正在尝试删除_ [[模板]]文本,并将[[bid_id]]替换为数字。我试过这个:

var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true) 
var new_bid_id = 2

var new_oh = bid_template.outerHTML

new_oh = new_oh.replace(/_\[\[template\]\]/g, '')
new_oh = new_oh.replace(/\[\[bid_id\]\]/g, new_bid_id)

此时如果我是console.log new_oh,那正是我想要的 - 一切都被正确替换。然而下一行...

var new_bid = document.createElement('div')
new_bid.outerHTML = new_oh

当我尝试设置outerHTML时,没有任何事情发生。如果我设置innerHTML它确实有效,但我更喜欢设置outerHTML。我没有收到任何错误消息,我无法弄清楚为什么它没有设置outerHTML。

2 个答案:

答案 0 :(得分:2)

我假设发生了错误:那个&lt;外部HTML&#39;属性&#39;元素&#39;,所以元素没有父节点。

如果您想使用新的div创建它,那么:

var div = document.createElement('div');

div.innerHTML = output;
document.body.appendChild(div);

如果没有:那么试试这个

&#13;
&#13;
var bid_template = document.getElementById('bid_wrapper_[[bid_id]]_[[template]]').cloneNode(true);
var new_bid_id = 2;
var parent = document.querySelector('.parent');
var new_oh = bid_template.outerHTML;


var output = new_oh.replace(/_\[\[template\]\]/g, '');
output = output.replace(/\[\[bid_id\]\]/g, new_bid_id);

parent.innerHTML = output;
alert(output)
&#13;
<div class="parent">
  <div id="bid_wrapper_[[bid_id]]_[[template]]">
    <div class="form_item_block" id="bid_wrapper_[[bid_id]]_[[template]]">
      <div id="bid_delete_[[bid_id]]_[[template]]">
        <img src="/images/icons/cross.png">
      </div>
      <div id="bid_label_wrapper_[[bid_id]]_[[template]]">Bid #1</div>
      <div>
        <input type="text" name="bid_summary" id="bid_summary_[[bid_id]]_[[template]]">
      </div>
      <div>
        <input name="bid_price" id="bid_price_[[bid_id]]_[[template]]">
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要先将new_bid div插入或附加到文档中,然后重置其outerHTML。

相关问题