动态添加html元素
生活随笔
收集整理的這篇文章主要介紹了
动态添加html元素
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
document.createElement()創(chuàng)建元素,再用appendChild( )添加
動(dòng)態(tài)引入jquery:
var scriptElement=document.createElement("script"); scriptElement.type="text/javascript"; scriptElement.src="https://code.jquery.com/jquery-3.4.1.min.js"; scriptElement.charset="utf-8"; document.getElementsByTagName('head')[0].appendChild(scriptElement);如果屬性有特殊字符怎么辦(比如屬性名為http-equiv)?使用setAttribute方法添加屬性。動(dòng)態(tài)添加meta元素,指定5秒后刷新:
var meta=document.createElement("meta"); meta.setAttribute("http-equiv","refresh"); meta.setAttribute("content","5"); document.getElementsByTagName('head')[0].appendChild(meta);使用innerHTML
使用innerHTML就隨意的多了,將要添加的html拼成字符串即可。替換html > body中的內(nèi)容:
var bodyElement = document.getElementsByTagName("body"); bodyElement[0].innerHTML = "<H1>Hello World!</H1>";jQuery
jQuery封裝了很對(duì)好用的方法,動(dòng)態(tài)添加更隨意。替換html > body中的內(nèi)容:
var newElement= $("<H1>Hello World!</H1>"); $("body:first").append(newElement);總結(jié)
以上是生活随笔為你收集整理的动态添加html元素的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: chrome urls
- 下一篇: 动态引入/添加js脚本