jQuery对象和原生jsDOM对象相互转换(含测试用例)

本博文源于jquery基础,旨在讨论如何完成其两者的转换

jQuery对象转换为Js dom对象

只需书写方括号枚举其中一项的下标即可:

$("box")[0].style.backgroundColor = "red";

测试代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box {
				width: 100px ;
				height: 100px;
				background-color: gray;
				float: left;
				margin-right: 10px;
			}
		</style>
	</head>
	<body>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<script type="text/javascript" src="./jquery-3.5.1.min.js"></script>
		<script type="text/javascript">
			$(".box")[0].style.backgroundColor = "red";
			$(".box")[1].style.backgroundColor = "green";
			$(".box")[2].style.backgroundColor = "blue";
			$(".box")[3].style.backgroundColor = "orange";
			$(".box")[4].style.backgroundColor = "gold";
			

		</script>
	</body>
</html>

测试结果

jQuery对象和原生jsDOM对象相互转换(含测试用例)_第1张图片

原生js dom对象转换为jQuery对象

通过getElement等方法转化为js dom对象,然后传入jquery括号里即可

var oBox = document.getElementsByClassName("box");
$(oBox).css("backgroundColor","grey");
			

测试代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box {
				width: 100px ;
				height: 100px;
				background-color: gray;
				float: left;
				margin-right: 10px;
			}
		</style>
	</head>
	<body>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<div class="box"></div>
		<script type="text/javascript" src="./jquery-3.5.1.min.js"></script>
		<script type="text/javascript">
			var oBox = document.getElementsByClassName("box");
			$(oBox).css("backgroundColor","grey");
			
		</script>
	</body>
</html>

测试结果

jQuery对象和原生jsDOM对象相互转换(含测试用例)_第2张图片

你可能感兴趣的:(JS基础)