Javascript append HTML to a variable that holds HTML

Viewed 3613

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

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

Here is the working example, if anything isn't clear, feel free to ask:

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)
<div id="final"></div>

You can create an in memeory DOM element and work with that:

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

Related