在javascript中将HTML元素附加到当前元素

时间:2017-05-06 09:55:16

标签: javascript dom append href

我的代码如下:

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中创建了一个标签。我想在迭代中的a标签前面添加一个数字计数器。意思是,第一个标签将具有数字1然后再打开。

我尝试使用$ index = 1然后尝试附加$ index ++。

但是,我想在a或p标签内添加索引号。怎么办呢。

期待

由于

杰夫

2 个答案:

答案 0 :(得分:1)

尝试创建span元素并将其作为子项追加到循环中 -

var spanElem = document.createElement("span");
var cloneElem = node.cloneNode(true);
spanElem.innerHTML = $index++;
cloneElem.href = "somelink url"
cloneElem.appendChild(spanElem);
mElem.appendChild(cloneElem);

答案 1 :(得分:1)

&#13;
&#13;
function addElem() {
  var mElem = document.querySelector('.post_description');
  var hElems = document.getElementsByTagName('H3');

  for (var i = 0; i < hElems.length; i++) {
    var node = document.createElement("a");
    node.innerHTML = i + 1 + '. ' + hElems[i].innerHTML;
    mElem.appendChild(node);
  }
};

addElem()
&#13;
.post_description {
  height: 150px;
  width: 150px;
  background-color: green;
  position: absolute;
  right: 0;
  top: 0;
}

.post_description a {
  display: block;
}
&#13;
<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>
&#13;
&#13;
&#13;