2 回答
TA贡献1780条经验 获得超1个赞
使用classList.add()添加类
按类查询元素时使用点 (.)
querySelector()
更改
div1.appendChild(div1)
为div1.appendChild(div2)
我添加了一些 CSS 来可视化结果。
var row1 = document.querySelector('.row');
var div1 = document.createElement('div');
div1.classList.add('col', 's12', 'm6');
var div2 = document.createElement('div');
div2.classList.add('card', 'blue-grey', 'darken-1');
var div3 = document.createElement('div');
div3.classList.add('card-content', 'white-text');
var span1 = document.createElement('span');
span1.classList.add('card-title');
span1.textContent = 'Card Title';
var para = document.createElement('p');
var paracontent = document.createTextNode('this is new world');
para.appendChild(paracontent);
div3.appendChild(span1);
div3.appendChild(para);
div2.appendChild(div3);
div1.appendChild(div2);
row1.appendChild(div1);
.row {
background: red;
padding: 0 15px 15px;
}
.row::before {
content: 'class="row"';
color: white;
}
.col {
background: white;
padding: 0 15px 15px;
}
.col::before {
content: 'class="col s12 m6"';
color: white;
color: red;
}
.blue-grey {
background: blue;
padding: 0 15px 15px;
}
.blue-grey::before {
content: 'class="card blue-grey darken-1"';
color: white;
}
.white-text {
background: green;
padding: 15px;
color: white;
}
.card-title {
font-weight: bold;
padding: 5px;
background: white;
color: green;
display: block;
}
<div class="row"></div>
TA贡献1780条经验 获得超3个赞
您必须使用setAttribute方法来设置class和修复您的div1.appendChild(div1);代码:
var row1 = document.querySelector('.row');
var div1 = document.createElement('div');
div1.setAttribute("class", 'col s12 m6');
var div2 = document.createElement('div');
div2.setAttribute("class", 'card blue-grey darken-1');
var div3 = document.createElement('div');
div3.setAttribute("class", 'card-content white-text');
var span1 = document.createElement('span');
span1.setAttribute("class", 'card-title');
var para = document.createElement('p');
var paracontent = document.createTextNode('this is new world');
para.appendChild(paracontent);
div3.appendChild(para);
div2.appendChild(div3);
div1.appendChild(div2);
row1.appendChild(div1);
- 2 回答
- 0 关注
- 89 浏览
添加回答
举报