简体   繁体   中英

Error while trying to create new element

I use the following code and I got error when I do appendChild

$('#tra').on('click', function() {
    transpile(source.val())

// ...
var display = $('#display');
diff.forEach(function(part) {

 var span = document.createElement('span');
        span.style.color = color;
        span.appendChild(document
            .createTextNode(part.value));
        display.appendChild(span);

In the last code I got error:

main.js:42 Uncaught TypeError: display.appendChild is not a function ,what it can be?

in the index.html I've the display as follows

Your display variable is a jQuery object. It has a .append() method that should be fine for what you need.

display.append(span);

If you want to use the JavaScript DOM function .appendChild() instead, you need to extract the DOM element from display first:

display.get(0).appendChild(span);

First, check if your #display element exists in your document (DOM).

Second, there is no appendChild method in jQuery, so you should use:

display.append(span)

Or

$(span).appendTo(display);

Otherwise, if you want to use appendChild anyway, you'd use:

display[0].appendChild(span);

Or by using $.get method:

display.get(0).appendChild(span);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM