Reputation: 4766
I am dynamically generating a string which contains the code of HTML form element. Then I want to set this element as a child element to an existing node. Following is my code.
$('#parentNode')[0].append(render(content))
And it's output is following - You can see appended double-quotation marks
<html>
<div id='MatchMakingResults'>
"<form>Dynamic child node</form>"
</div>
</html>
I tried $('#parentNode')[0]append($.parseHTML(render(content));
But then it encodes the string as an object. How can I remove these double-quotation marks from the added element?
Upvotes: 1
Views: 1660
Reputation: 15120
In addition to the answer from @OriDrori (which should clear up your confusion), you can also just set the innerHTML
property instead so you do not have to parse the string (this would make more sense if you were to jettison the jquery and just use vanilla js). For example:
const childNode = '<form>Dynamic child node</form>';
$('#parentNode')[0].innerHTML = childNode;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentNode"></div>
Upvotes: 2
Reputation: 191976
You want to use jQuery's .append()
instead of the native DOM ParentNode.append()
. The jQuery's method can convert a complicate string to HTML.
To do so, remove the [0]
from the call, because it refers to the DOM node, and then you use the native DOM append.
var content = '<form>Dynamic child node</form>';
$('#MatchMakingResults').append(render(content));
function render(content) {
return content;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MatchMakingResults"></div>
Using the native DOM append, you can see it added as a string:
var content = '<form>Dynamic child node</form>';
$('#MatchMakingResults')[0].append(render(content));
function render(content) {
return content;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="MatchMakingResults"></div>
Upvotes: 1