Javascript: Unexpected Token ILLEGAL Error with appendChild()

浪尽此生 提交于 2019-12-24 05:23:08

问题


I'm new to javascript, but I'm getting an "Unexpected Token ILLEGAL" error with this line of code:

switch (city) {
    case "london":
        var newdiv = document.createElement('<div id="london" class="option-area"><label class="city">From London to…?</label>
                <select class="city">
                    <option></option>
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                </select><br /></div>');

        document.all.bookingform.appendChild(newdiv);
        break;
}

It's probably a very dumb mistake, but I've tried for hours to get this block working. Please help!


回答1:


There are a couple errors in your code:

1) The document.createElement() function takes a single argument as the element name, not an HTML/XML snippet to parse and build a DOM tree. However you chould achieve your goal by building an anonymous wrapper element and setting its inner HTML, then appending its first child to the target element, for example:

var wrapperDiv = document.createElement("div");
wrapperDiv.innerHTML = '<div id="london" class="option-area"><label...';
document.all.bookingform.appendChild(wrapperDiv.firstChild);

2) Strings cannot span multiple lines but you can build a multiline string like this:

var str = '<div id="london" class="option-area">' +
          '  <label class="city">From London to…?</label>' +
          '  <select class="city">' + // ...
          '</div>';

If you actually want newlines in the string you can use the newline escape sequence (\n) in a string literal, like 'Hello\nnewline!'.

[Edit]

Of course, if you're just trying to append HTML to an element already in the document body you do this:

var mydiv = document.getElementById('mydiv');
if (mydiv) {
  mydiv.innerHTML += '<div class="newdiv">' +
                     ' New child will be appended...' +
                     '</div>';
}

Note however that there are quirks in various browsers when modifying forms such as above; consider using a JavaScript library such as jQuery, ExtJS, or Prototype.js.




回答2:


document.createElement is used to create one element - like document.createElement('div'), so passing HTML is not allowed. You could create the element, then change the HTML for it later with ref_to_the_div.innerHTML = "<some html="goes here" />"



来源:https://stackoverflow.com/questions/7457182/javascript-unexpected-token-illegal-error-with-appendchild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!