Cant append parsed HTML with appendChild to a div

Viewed 173

Why cant I append pasted html with appendChild? This is my code:

<div id="byeeee"></div>

var appenddescription = $.parseHTML("<h1>hello</h1> bye<br>");

document.getElementById("byeeee").appendChild(appenddescription);

My goal is to parse the html and append it to the div. When I try the code above I get the following error:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I tried to use this answer https://stackoverflow.com/a/31800768/15677215 but it didnt help

P.S: I'm using Jinja as a templating engine. In my real code the JavaScript would look like

var appenddescription = $.parseHTML("{{hello}}");
1 Answers

If you're going to use jQuery, it's discouraged to mix it with JS. Use jQuery's .append() like so:

var appenddescription = $.parseHTML("<h1>hello</h1> bye<br>");
$("#byeeee").append(appenddescription);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="byeeee"></div>

To turn off HTML escaping in Jinja, use:

var appenddescription = $.parseHTML("{{hello|safe}}");

jQuery.parseHTML() | jQuery API Documentation

Related