This and the DOM
The this
keyword always has a relative meaning; it depends on the exact context it is in. In the DOM, the special this
keyword refers to the element of the DOM it belongs to. If we specify an onclick
to send this
in as an argument, it will send in the element the onclick
is in.
Here is a little HTML snippet with JavaScript in the script
tag:
<!DOCTYPE html>
<html>
<body>
<script>
function reveal(el){
console.log(el);
}
</script>
<button onclick="reveal(this)">Click here!</button>
</body>
</html>
And this is what it will log:
<button onclick="reveal(this)">Click here!</button>
As you can see, it is logging the element it is in, the button
element.
We can access the parent of this
with a function like this:
function reveal(el){
console.log(el.parentElement);
}
In the above example, the body is the parent of...