Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript append HTML to a variable that holds HTML

I have Javascript variable let's say named HTMLvar that holds HTML code meaning if i

console.log(HTMLvar)

i get this result so the variable holds pure HTML code:

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

what i want is to append some data (HTML)

var HTMLnewdata = MY NEW APPENDED DATA HERE

at the beginning of the div with id=msgscntr. so the result after appending that data will be something like this when i console log that HTMLvar again.

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

i hope you guys understand what i'm trying to achieve here, using Javascript of course. thanks in advance

like image 867
ler Avatar asked Aug 13 '26 13:08

ler


1 Answers

I am assuming HTMLvar is a string.

// 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;
like image 123
AndreFeijo Avatar answered Aug 15 '26 04:08

AndreFeijo