一、添加到html dom,通过.append()/appendTO()添加到dom
image.png
1-1:第一个demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询DOM信息</title>
<link rel = "stylesheet" href="">
<script src = ./js/jquery-3.4.1.min.js type = "text/javascript"></script>
</head>
<body>
<input type = "text" name="username" id = "username" class = "input-text" my-user="张三" value="我的用户名">
<input type = "password" name="password" >
<p class="area city">广州</p>
<p style="color:#f00;">深圳</p>
<p class="area">长沙 <span>测试数据:</span></p>
<p class="area" id = 'beij'>北京</p>
<p class="info" id = "info">
查看详细
<span>内容:</span>
<small>文字描述</small>
</p>
<script>
$(document).ready(function(){
var pList = $('p');
// 构建dom对象
var htmlDom = $('<p class = "test"/>');
console.log(htmlDom);
// 添加到html dom中 第一种方法
// html.appendTo('body');
// 添加到html dom中,第二种方法
$('body').append(htmlDom);
})
//
</script>
</body>
</html>
image.png
二、添加到html dom,通过.html()/.text()/.val()/.attr()设置内容,此方法添加后为覆盖,比如id=‘beij’的北京文字被span覆盖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询DOM信息</title>
<link rel = "stylesheet" href="">
<script src = ./js/jquery-3.4.1.min.js type = "text/javascript"></script>
</head>
<body>
<input type = "text" name="username" id = "username" class = "input-text" my-user="张三" value="我的用户名">
<input type = "password" name="password" >
<p class="area city">广州</p>
<p style="color:#f00;">深圳</p>
<p class="area">长沙 <span>测试数据:</span></p>
<p class="area" id = 'beij'>北京</p>
<p class="info" id = "info">
查看详细
<span>内容:</span>
<small>文字描述</small>
</p>
<script>
$(document).ready(function(){
var pList = $('p');
// 构建dom对象
var htmlDom = $('<p class = "test"/>');
// 在dom中添加内容
htmlDom.html('<span>我是新加的</span>');
$('body').append(htmlDom);
$('#beij').html('<span>我是新加的</span>');
$('#beij').attr("areaId","666");
})
//
</script>
</body>
</html>
运行结果
三、添加到html dom,css()添加css/.addClass()、.removeClass()类操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询DOM信息</title>
<link rel = "stylesheet" href="">
<script src = ./js/jquery-3.4.1.min.js type = "text/javascript"></script>
</head>
<body>
<input type = "text" name="username" id = "username" class = "input-text" my-user="张三" value="我的用户名">
<input type = "password" name="password" >
<p class="area city">广州</p>
<p style="color:#f00;">深圳</p>
<p class="area">长沙 <span>测试数据:</span></p>
<p class="area" id = 'beij'>北京</p>
<p class="info" id = "info">
查看详细
<span>内容:</span>
<small>文字描述</small>
</p>
<script>
$(document).ready(function(){
// 添加新的class
$('#beij').addClass('666');
// 移除class
$('#beij').removeClass("area");
// 操作css样式
$('#beij').css({
'color':'#0f0',
'background-color':'#000',
});
// 隐藏元素
$('#info').hide();
// 显示元素
$('#info').show();
})
//
</script>
</body>
</html>
image.png
网友评论