简体   繁体   English

在 JS 中创建 HTML 元素(没有 jQuery)? 我究竟做错了什么?

[英]Creating HTML elements in JS (without jQuery)? What am I doing wrong?

I'm new to node.js.我是 node.js 的新手。 Here is my code:这是我的代码:
My Code我的代码

More specifically, here is what I have for JS:更具体地说,这是我对 JS 的看法:

let torontoTeams = [
    {"name": "Raptors", "description": "The Raptors compete in the National Basketball Association (NBA), as a member club of the league's Eastern Conference Atlantic Division."},

    {"name": "Maple Leafs", "description": "The Maple Leafs are one of the 'Original Six' NHL teams, and have won the Stanley Cup 13 times."},

    {"name": "Blue Jays", "description": "The Blue Jays compete in Major League Baseball (MLB) as a member club of the American League (AL) East division."}
];
for (let i=0; i < torontoTeams.length; i++) {

    let newSection = document.createElement('section');
    document.appendChild(newSection);

    let newTeam = document.createElement('h1');
    newTeam.appendChild(document.createTextNode(torontoTeams[i].name));

    let newDesc = document.createElement('P');
    newDesc.appendChild(document.createTextNode(torontoTeams[i].description));

    document.createElement(newSection);
    newSection.appendChild(newTeam);
    newSection.appendChild(newDesc);
};

I'm not sure where I'm going wrong with creating the HTML elements.我不确定在创建 HTML 元素时我哪里出错了。

You can append only one element to document .您只能将一个元素附加到document Append the section s to document.body or create a container and target it with document.querySelectorsection s 附加到document.body或创建一个容器并使用document.querySelector将其作为目标

 var body = document.body, torontoTeams = [ {"name": "Raptors", "description": "The Raptors compete in the National Basketball Association (NBA), as a member club of the league's Eastern Conference Atlantic Division."}, {"name": "Maple Leafs", "description": "The Maple Leafs are one of the 'Original Six' NHL teams, and have won the Stanley Cup 13 times."}, {"name": "Blue Jays", "description": "The Blue Jays compete in Major League Baseball (MLB) as a member club of the American League (AL) East division."} ]; for (let i=0; i < torontoTeams.length; i++) { var newSection = document.createElement('section'); body.appendChild(newSection); // append to body. var newTeam = document.createElement('h1'); newTeam.appendChild(document.createTextNode(torontoTeams[i].name)); var newDesc = document.createElement('P'); newDesc.appendChild(document.createTextNode(torontoTeams[i].description)); // document.createElement(newSection); What is this suppose to do? It doesn't work. newSection.appendChild(newTeam); newSection.appendChild(newDesc); };
 section { display: block; width: 100vh; height: 33vh; background-color: blue; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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