js動態添加html標簽和屬性_手動插入meta、script、div、img等標簽


web網頁是由 html標簽一層層組成的,js也可以動態添加對應的標簽,比如mate標簽、script標簽、div標簽、img標簽等,動態創建的方法基本都差不多,下面將簡單介紹下如何實現

 

一:手動添加mate標簽

function addMeta(name,content){//手動添加mate標簽
	let meta = document.createElement('meta');
    meta.content=content;
    meta.name=name;
    document.getElementsByTagName('head')[0].appendChild(meta);
}

  

 

二:手動添加script標簽

function addScript(src){//手動添加script標簽
	let script=document.createElement("script");
    script.type="text/JavaScript";
    script.src= src;
    document.getElementsByTagName('head')[0].appendChild(script);
}

  

 

三:動態添加元素div

function adddiv(pid,html,attr){//動態添加元素div
	 attr=attr || {};
    let parent = document.getElementById(pid);
    let div = document.createElement("div");//添加 div
	 for(let i in attr){//設置 div屬性
	 	div.setAttribute(i,attr[i]);
	 } 
    div.innerhtml = html;
    parent.appendChild(div);
}
addDiv("pid","<p>動態添加的div</p>",{"id":"newDiv"});//調用

  

攝圖網https://www.wode007.com/sites/73204.html VJ師網https://www.wode007.com/sites/73287.html

四:動態添加元素img標簽

function addImg(pid,src,attr){//動態添加元素img標簽
	attr=attr || {};
   let parent = document.getElementById(pid);
   let img = document.createElement("img");//添加 div
   for(let i in attr){//設置 div屬性
	 	img.setAttribute(i,attr[i]);
	}
   img.src = src;
   parent.appendChild(img);
}
 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。