Reputation: 11
is it possible to add an HTML code to HTML with javascript.?
because I have this code, it generated automatically like this:
<div class="investi-announcements-summary" data-investi-date-format="dd MMM yyyy" data-investi-num-announcements="100" data-investi-filter-regex=".*presentation">
<div>28 Jun 2021</div>
<h4><a href="http://www.example.com" target="_blank">Investor Presentation - June 2021</a></h4>
</div>
And I want to add this code <div class="content">
before <div>28 Jun 2021</div>
and this code </div>
after <h4></h4>
so it'll be like this:
<div class="investi-announcements-summary" data-investi-date-format="dd MMM yyyy" data-investi-num-announcements="100" data-investi-filter-regex=".*presentation">
<div class="content">
<div>28 Jun 2021</div>
<h4><a href="http://www.example.com" target="_blank">Investor Presentation - June 2021</a></h4>
</div>
</div>
if it's possible, I hope someone can help me on that.
Thank you,
Upvotes: 0
Views: 63
Reputation: 351
const mainEl = document.querySelector('.investi-announcements-summary')
let contentEl = document.createElement('div')
contentEl.classList.add('content')
for (let child of mainEl.children) contentEl.appendChild(child.cloneNode(true))
mainEl.innerHTML = ''
mainEl.appendChild(contentEl)
<div class="investi-announcements-summary" data-investi-date-format="dd MMM yyyy" data-investi-num-announcements="100" data-investi-filter-regex=".*presentation">
<div>28 Jun 2021</div>
<h4><a href="http://www.example.com" target="_blank">Investor Presentation - June 2021</a></h4>
</div>
Upvotes: 1
Reputation: 10221
Yes, it's possible. In this particular example you can replace innerHTML
of outer div.investi-announcements-summary
with newly created div
:
const box = document.querySelector(".investi-announcements-summary"),
newDiv = document.createElement("div");
newDiv.className = "content";
/* copy content of original div */
newDiv.innerHTML = box.innerHTML;
/* replace content of original div with new div */
box.innerHTML = newDiv.outerHTML;
document.getElementById("res").value = box.outerHTML;
body
{
height: 100vh;
}
<div class="investi-announcements-summary" data-investi-date-format="dd MMM yyyy" data-investi-num-announcements="100" data-investi-filter-regex=".*presentation">
<div>28 Jun 2021</div>
<h4><a href="http://www.example.com" target="_blank">Investor Presentation - June 2021</a></h4>
</div>
<textarea id="res" readonly="true" style="width: 100%; height: 50%"></textarea>
But you should check out some tutorials on how to add/replace DOM elements
Upvotes: 1