您好我是新手并尝试创建DOM,但是我遇到了与appendChild的奇怪问题,而第一次尝试和第二次它有效,但第三次我完全不知道。 这是我的HTML:
<html>
<head>
<title>Tugas Anchor DOM!</title>
</head>
<body>
<div id="main">
</div>
<script src="script.js"></script>
</body>
</html>
我将使用DOM将HTML转换为:
<html>
<head>
<title>Tugas Anchor DOM!</title>
</head>
<body>
<div id="main">
<div id="content">
<div class="content-post">
<h1>Judul Post</h1> <!-- IM STUCK HERE -->
<button class="share-post-btn">Share this Post</button>
</div>
<div class="content-post">
<h1>Judul Post 2</h1>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
但我坚持为h1
创建一个新的appendChild,这也是DOM的另一个newChild。
这是我的js:
var menu = document.getElementById("main");
var mainDiv = document.createElement("div");
var newDiv1 = document.createElement("div");
var newDiv2 = document.createElement("div");
var newH1 = document.createAttribute("h1");
var newButton = document.createAttribute("button");
var createId = document.createAttribute("id");
var createAtt = document.createAttribute("class");
createId.value ="content";
createAtt.value = "content-post";
//top
mainDiv.setAttributeNode(createId);
menu.appendChild(mainDiv);
//1st
newDiv1.setAttribute('class','content-post');
mainDiv.appendChild(newDiv1);
var judul1 = newDiv1.appendChild(newH1); //appendChild can't be executed here ?
// judul1.innerHTML = "Judul Post";
//2nd
newDiv2.setAttribute('class','content-post');
mainDiv.appendChild(newDiv2);
答案 0 :(得分:1)
window.location.href = "products.html";
document.createElement
代替document.createAttribute
代替h1, span, p
你应该这样做:
var mainDiv = document.getElementById('main');
var contentDiv = document.createElement('div');
var contentPostDiv1 = document.createElement('div');
var contentPostDiv2 = document.createElement('div');
var judul1 = document.createElement('h1');
var judul2 = document.createElement('h1');
var button = document.createElement('button');
contentDiv.setAttribute('id', 'content');
mainDiv.appendChild(contentDiv);
contentPostDiv1.setAttribute('class','content-post');
contentPostDiv2.setAttribute('class','content-post');
contentDiv.appendChild(contentPostDiv1);
contentDiv.appendChild(contentPostDiv2);
judul1.innerHTML = 'Judul Post'
button.setAttribute('class', 'share-post-btn');
button.innerHTML = 'Share this Post'
contentPostDiv1.appendChild(judul1);
contentPostDiv1.appendChild(button);
judul2.innerHTML = 'Judul Post 2';
contentPostDiv2.appendChild(judul2);