我的代码如下追加一个HTML元素到当前元素以JavaScript
function addElem(){
var mElem = document.querySelector('.post_description')
var hElems = document.getElementsByTagName('H3');
var $index=1;
var node = document.createElement("a");
for(var i=0;i<hElems.length;i++){
//console.log(hElems[i].innerHTML);
var textnode = document.createTextNode(hElems[i].innerHTML);
var cloneElem = node.cloneNode(true);
cloneElem.appendChild(textnode);
mElem.appendChild(cloneElem);
mElem.appendChild($index++);
}
};
addElem()
.post_description{
height: 150px;
width:150px;
background-color:green;
position:absolute;
right:0;
top:0;
}
.post_description a{
display:block;
}
<div class="mg_post_description">
<div class="main_body">
<h3>Testing one</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. ng essentially unchanged</p>
<h3>Testing two</h3>
<p>Lorem Ipsum is simply Lorem including versions of Lorem Ipsum.</p>
<h3>Testing three</h3>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem of Lorem Ipsum.</p>
</div>
</div>
<div class="post_description"></div>
这里,我已经提取从内容H3标记给出,并且在“post_description”附加到创建的标签DIV。我想在迭代中的标签前添加一个数字计数器。意思是,第一个标签会有数字1,然后打开。
我试图使用$ index = 1,然后试图追加$ index ++。
不过,我想在a或p标签内添加索引号。如何才能做到这一点。
期待
感谢
杰夫
谢谢你的回答。 – jeff