Search code examples
javascriptdomappendhref

Appending an HTML element to current element in javascript


My code is given below

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>

Here I have extracted h3 tags from the content and appended to created a tags in the 'post_description' div. I would like to add a number counter in front of the a tags in the iteration. Meaning, the first a tag will have number 1 and then on.

I attempted using $index=1 and then attempted appending the $index++.

However, I would like to add the index number inside the a or p tags. How can this be done.

Looking forward

Thanks

jeff


Solution

  • 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()
    .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>