Home > Article > Web Front-end > jquery creates DOM elements
jquery creates DOM elements
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>创建DOM元素</title> </head> <body> </body> </html>
Creating new elements is very troublesome to operate natively
The first step: Create new elements
var img = document.createElement('img')
The second step is for new elements Add content or attributes to elements
img.src = '../images/zly.jpg' img.width = 200 img.style.borderRadius = '10%' img.style.boxShadow = '3px 3px 3px #888'
The third step: Add new elements to the page
document.body.appendChild(img)
Using jquery will greatly simplify these operations
It can also be divided into three steps
The first step: Create a new element, at least a pair of tags, the angle brackets must not be omitted
var img = $('<img>') var img = $('<img src="../images/zly.jpg" width="200">') img.appendTo('body')
The second step: Add content or attributes to the new element
img.attr('src', '../images/zly.jpg') img.css('width',200) img.css('border-radius','10%') img.css('box-shadow','3px 3px 3px #888')
Three steps: Add to the page
img.appendTo('body')
The above steps can be simplified: use jquery’s unique chain operation to complete, change a star
$('<img>').attr('src', '../images/gyy.jpg').css('width','200px').css('border-radius','10%').css('box-shadow','3px 3px 3px #888').appendTo('body')
In fact, when using the $() function to create elements, You can also pass in the second parameter and set the properties directly. Let’s further simplify these codes
$('<img>',{ src: '../images/gyy.jpg', title: '我是高圆圆', style: 'width:200px;border-radius:10%;box-shadow:3px 3px 3px #888', click: function(){alert($(this).attr('title'))} }).appendTo('body')
The above is the detailed content of jquery creates DOM elements. For more information, please follow other related articles on the PHP Chinese website!