Home > Web Front-end > JS Tutorial > jquery creates DOM elements

jquery creates DOM elements

无忌哥哥
Release: 2018-06-29 14:19:38
Original
5131 people have browsed it

jquery creates DOM elements

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>创建DOM元素</title>
</head>
<body>
</body>
</html>
Copy after login

Creating new elements is very troublesome to operate natively

The first step: Create new elements

var img = document.createElement(&#39;img&#39;)
Copy after login

The second step is for new elements Add content or attributes to elements

img.src = &#39;../images/zly.jpg&#39;
img.width = 200
img.style.borderRadius = &#39;10%&#39;
img.style.boxShadow = &#39;3px 3px 3px #888&#39;
Copy after login

The third step: Add new elements to the page

document.body.appendChild(img)
Copy after login

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 = $(&#39;<img>&#39;)
var img = $(&#39;<img src="../images/zly.jpg" width="200">&#39;)
img.appendTo(&#39;body&#39;)
Copy after login

The second step: Add content or attributes to the new element

img.attr(&#39;src&#39;, &#39;../images/zly.jpg&#39;)
img.css(&#39;width&#39;,200)
img.css(&#39;border-radius&#39;,&#39;10%&#39;)
img.css(&#39;box-shadow&#39;,&#39;3px 3px 3px #888&#39;)
Copy after login

Three steps: Add to the page

img.appendTo(&#39;body&#39;)
Copy after login

The above steps can be simplified: use jquery’s unique chain operation to complete, change a star

$(&#39;<img>&#39;).attr(&#39;src&#39;, &#39;../images/gyy.jpg&#39;).css(&#39;width&#39;,&#39;200px&#39;).css(&#39;border-radius&#39;,&#39;10%&#39;).css(&#39;box-shadow&#39;,&#39;3px 3px 3px #888&#39;).appendTo(&#39;body&#39;)
Copy after login

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

$(&#39;<img>&#39;,{
src: &#39;../images/gyy.jpg&#39;,
title: &#39;我是高圆圆&#39;,
style: &#39;width:200px;border-radius:10%;box-shadow:3px 3px 3px #888&#39;,
click: function(){alert($(this).attr(&#39;title&#39;))}
}).appendTo(&#39;body&#39;)
Copy after login

The above is the detailed content of jquery creates DOM elements. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template