can't change outerHTML with javascript

落花浮王杯 提交于 2021-01-28 21:29:32

问题


I have this HTML template on a page:

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

I'm trying to strip out the _[[template]] text, and also replace the [[bid_id]] with a number. I tried this:

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)

At this point if I console.log new_oh, it is exactly what I want - everything is replaced correctly. However the next lines...

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

Nothing happens here when I try to set the outerHTML. It does work if I set the innerHTML, but I would prefer to set the outerHTML. I don't get any error messages, and I can't figure out why it's not setting the outerHTML.


回答1:


I assuming the error has occurred : that 'outerHTML' property on 'Element', so element has no parent node.

if you want to create it with new div, then :

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

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

if not : then try this

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



回答2:


You need to insert or append the new_bid div to the document first, then reset its outerHTML.



来源:https://stackoverflow.com/questions/37190395/cant-change-outerhtml-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!