1

I have the following code (which is the HTML from the example):

var modal=
        '<div class="modal fade" id="infoModal"'+id+'tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">'
        +'<div class="modal-dialog">'
        +'<div class="modal-content">'
        +'<div class="modal-header">'
        +'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'
        +'<h4 class="modal-title">Modal title</h4>'
        +'</div>'
        +'<div class="modal-body">'
        +'<p>One fine body&hellip;</p>'
        +'</div>'
        +'<div class="modal-footer">'
        +'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'
        +'<button type="button" class="btn btn-primary">Save changes</button>'
        +'</div>'
        +'</div>'
        +'</div>'
        +'</div>';
        document.body.appendChild(modal);

And I get the error:

Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.

If I put the same HTML inside my index.html it works just fine. What's the problem here?

1
  • A string is not a node. -- "Adds a node to the end of the list of children of a specified parent node" -- MDN Commented Jan 19, 2014 at 20:39

1 Answer 1

3

modal is not an element. It is just a string. appendChild expects an actual element reference, not just a string.

While I don't suggest it, you could do

document.body.innerHTML = document.body.innerHTML+modal;

This is lame and will remove your event listeners from anything in the body.

You could also do something like:

var div = document.createElement('div');
div.innerHTML = modal;
document.body.appendChild(div);

Live demo (click).

If I had that amount of markup in string form, I would just put it in an html file and either include it from the server or load it with javascript via ajax.

You could also create the whole structure using document.createElement for each piece.

Sign up to request clarification or add additional context in comments.

1 Comment

@DatProgram it also looks like you're missing a space after "id" and before "tabindex"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.