0

Hello everybody, so iam Trying to insert an HTML Element into an another HTML Element using Javascript.

I Tried using .insertAdjacentHTML but it inserts it near to the target element as the positions isn't suitable for me... and .html inserts it as text format not HTML format

here is what i tried coding:-

   SendClientMessage(COLORS_.white, "15px", "none", '<div class="ls-files">' + CMDS_List + '</div>');
   function SendClientMessage(color, font, align = 'none', message)
   {
      if(align !== "none")
      {
         output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + '; text-align: ' + align + ';">' + message + '</p>'); 
      }
      else if(align === "none")
      {
         output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + ';">' + message + '</p>'); 
      }
   }

the output:-

<p style="color: #FFFFFF; font-size: 15px;"></p>
<div class="ls-files">clear,clock,dati,ping,uname,whoami,cmd,</div>
Zorono
  • 75
  • 2
  • 12
  • what is the expected output? – brk Dec 16 '17 at 18:11
  • `

    clear,clock,dati,ping,uname,whoami,cmd,
    `
    – Zorono Dec 16 '17 at 18:12
  • did u tried innerHTML or appendChild? – brk Dec 16 '17 at 18:20
  • `.insertAdjacentHTML("beforeend", ...)` acts, more or less, like `.appendChild()`. The output shown is therefore only possible if `output_` is not the `p` tag. – Andreas Dec 16 '17 at 18:31
  • @brk on trying to use appendChild i have got an error `Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.` so i searched for any smilliar question: https://stackoverflow.com/questions/27079598/uncaught-typeerror-failed-to-execute-appendchild-on-node-parameter-1-is-no but i couldn't insert any stylesheets with this one – Zorono Dec 17 '17 at 08:35

1 Answers1

1

You can only put inline elements like span or a into a p tag using insertAdjacentHTML because it is using an html parser that checks for properly formatted html before inserting the content.

let CMDS_List = 'clear,clock,dati,ping,uname,whoami,cmd,';

SendClientMessage('white', "15px", "none", '<span class="ls-files">' + CMDS_List + '</span>');

function SendClientMessage(color, font, align = 'none', message) {
  let output_ = document.getElementById('output');
  if (align !== "none") {
    output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + '; text-align: ' + align + ';">' + message + '</p>');
  } else if (align === "none") {
    output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + ';">' + message + '</p>');
  }
}
  body {
  background: #999;
<div id="output"></div>
JasonB
  • 6,243
  • 2
  • 17
  • 27