Javascript DOM How to - Insert after anchor tag








Question

We would like to know how to insert after anchor tag.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="payload">XXXXXXXX</div>
  <div id="target">
    <br />
    <br />
    <br />
    <br /> Content within the target. <a href="">Anchor</a>
  </div><!--from  ww w. j  a  v  a  2  s  .com-->
    <script type='text/javascript'>
    
    function insertAfter(addition,target) {
        var parent = target.parentNode;
        if (parent.lastChild == target) {
            parent.appendChild(addition);  
        } else {
            parent.insertBefore(addition,target.nextSibling);
        }
    }
    var payload = document.getElementById("payload");
    var target = document.getElementById("target");
    var anchors = target.getElementsByTagName("a");
    if (anchors.length > 0) {
        insertAfter(payload,anchors[0]);
    }
    
    </script>

</body>
</html>

The code above is rendered as follows: