using javascript's .insertBefore to insert item as last child

前端 未结 6 1013
梦谈多话
梦谈多话 2020-12-18 01:15

I so miss jQuery. I\'m working on a project where I need to get my hands dirty with good \'ol plain Javascript again.

I have this scenario:

parent
           


        
6条回答
  •  忘掉有多难
    2020-12-18 01:56

    I got this code is work to insert a link item as the last child

    var cb=function(){
        //create newnode
        var link=document.createElement('link');
        link.rel='stylesheet';link.type='text/css';link.href='css/style.css';
    
        //insert after the lastnode
        var nodes=document.getElementsByTagName('link'); //existing nodes
        var lastnode=document.getElementsByTagName('link')[nodes.length-1]; 
        lastnode.parentNode.insertBefore(link, lastnode.nextSibling);
    };
    
    var raf=requestAnimationFrame||mozRequestAnimationFrame||
        webkitRequestAnimationFrame||msRequestAnimationFrame;
    if (raf)raf(cb);else window.addEventListener('load',cb);
    

提交回复
热议问题