我有Javascript变量让我们说名为HTMLvar,其中包含HTML代码,如果我
的console.log(HTMLvar)
我得到这个结果,所以变量包含纯HTML代码:
<div id="erpage-messagespage" class="xhide">
lot of divs here
<div id="msgscntr">
lot of html divs here too
</div>
lot of divs here too
</div>
我想要的是附加一些数据(HTML)
var HTMLnewdata =我的新附加数据
在div的开头, id = msgscntr 。 因此,当我再次登录HTMLvar时,附加该数据后的结果将是这样的。
<div id="erpage-messagespage" class="xhide">
lot of divs here
<div id="msgscntr">
" MY NEW APPENDED DATA HERE "
lot of html divs here too
</div>
lot of divs here too
</div>
我希望你们明白我在这里想要实现的目标,当然是使用Javascript。提前谢谢
答案 0 :(得分:2)
我假设HTMLvar是一个字符串。
// Parse the string as HTML
var parser = new DOMParser();
var htmlDoc = parser.parseFromString(HTMLvar, 'text/html');
// Get your element
var msgCntr = htmlDoc.getElementById('msgscntr');
// Do your logic here, append whatever you need
// When you done this will return as string again
var HTMLnewdata = htmlDoc.body.innerHTML;
答案 1 :(得分:0)
以下是工作示例,如果有什么不清楚,请随时问:
var starterHtml = `
<div id="erpage-messagespage" class="xhide">
lot of divs here
<div id="msgscntr">
lot of html divs here too
</div>
lot of divs here too
</div>
`;
var index = starterHtml.indexOf('>')
var final = starterHtml.slice(0, index + 1) + "!!!CONTENT GOES HERE!!! <br>" + starterHtml.slice(index + 1);
var wrapper = document.getElementById('final');
wrapper.insertAdjacentHTML('afterend', final)
&#13;
<div id="final"></div>
&#13;
答案 2 :(得分:0)
您可以创建一个内存DOM元素并使用它:
var starterHtml = `
<div id="erpage-messagespage" class="xhide">
lot of divs here
<div id="msgscntr">
lot of html divs here too
</div>
lot of divs here too
</div>
`;
//Create a DOM element
var holder = document.createElement("div");
//Load it with your HTML
holder.innerHTML = starterHtml;
//Find your target element and insert your string
holder.querySelector("#msgscntr").innerHTML = "!!My New Awesome content<br>" + holder.querySelector("#msgscntr").innerHTML;
//Get the inner HTML back
var finalHtml = holder.innerHTML;
//and you're done
console.log(finalHtml);
&#13;