gpt4 book ai didi

javascript - 如何使用javascript dom编写多个div

转载 作者:行者123 更新时间:2023-11-28 14:07:09 24 4
gpt4 key购买 nike

我想使用javascipt Dom编写这个html代码(包含许多div,每个div有不同的类)

<div class="row">
<div class="col s12 m6">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Card Title</span>
<p>I am a very simple card. I am good at containing small effectively.</p>
</div>
</div>
</div>
</div>

检查我的尝试,但它不起作用

var row1 = document.querySelector('row');
var div1 = document.createElement('div');
div1.className('col s12 m6');
var div2 = document.createElement('div');
div2.className('card blue-grey darken-1');
var div3 = document.createElement('div');
div3.className('card-content white-text');
var span1 = document.createElement('span');
span1.className('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(div1);
row1.appendChild(div1);

最佳答案

  • 使用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>

关于javascript - 如何使用javascript dom编写多个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60951235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com