jQuery 创建一个div元素
创建一个使用jQuery的<div>
元素可以通过以下步骤完成。
步骤:
- 创建一个新的
<
div>元素。
* 选择一个父元素,把这个新创建的元素放在那里。
* 将创建的div元素放入父元素。
例子1:这个例子创建了一个
<
div>元素,并使用append()方法将该元素追加到父元素的末端。
<!DOCTYPE html>
<html>
<head>
<title>
Create div element using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#newElement {
height: 40px;
width: 100px;
margin: 0 auto;
color: white
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br><br>
<button onclick="insert()">
insert
</button>
<!-- Script to insert div element -->
<script>
function insert() {
$("#parent").append('<div id = "newElement">A '
+ 'Computer Science portal for geeks</div>');
}
</script>
</body>
</html>
HTML
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:这个例子创建了一个 <div>
元素,并使用prependTo()方法将该元素追加到父元素的开头。
<!DOCTYPE html>
<html>
<head>
<title>
Create div element using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
#parent {
height: 100px;
width: 300px;
background: green;
margin: 0 auto;
}
#newElement {
height: 40px;
width: 100px;
margin: 0 auto;
color: white
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<div id= "parent"></div>
<br><br>
<button onclick="insert()">
insert
</button>
<script>
function insert() {
('<div id = "newElement">A Computer Science portal'
+ ' for geeks</div>').prependTo(('#parent'));
}
</script>
</body>
</html>
HTML
输出:
- 在点击按钮之前。
- 点击该按钮后。