Programming in HTML with JavaScript and CSS3.
Using the this pointer with jQuery
Using the this pointer
The this pointer is a special object provided by the jQuery framework. When running selections against the DOM using jQuery, this refers to the object that it finds or the collection of objects that it finds.
It provides a short cut to accessing the item within the current context of jQuery filter.
The following code demonstrates the this keyword:
<script type="text/javascript">
$("document").ready(
function () {
$('#floorDiv').click(function () {
$(this).css("background-color", "red");
})
}
);
</script>
Selecting multiple element using this pointer
In more advanced scenarios, the result of the selector can return more than one element.
You can select all elements inside a specified element in the DOM using the each operator, which calls the callback function passed into it for each element that’s returned.
The following code finds all the div elements inside the div with id floorDiv:
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery-3.1.3.min.js" type="text/javascript"></script>
<style>
div {
width: 200px;
height: 200px;
background-color: green;
margin: 5px 5px 5px 5px;
}
</style>
</head>
<body>
<h4>Click on the Box</h4>
<div id="floorDiv"></div>
<div id="Div1"></div>
<div id="Div2"></div>
<div id="Div3"></div>
<script>
$("document").ready(
function () {
//returns all div's inside the div with id="floorDiv"
$('#floorDiv').click(function () {
$("div").each(function () {
$(this).css({
"background-color": "red",
"height": "100px",
"width": "100px"
});
});
})
}
);
</script>
</body>
Ads Right