Open In App

JavaScript- Reference the Current DOM Element in JS

Last Updated : 27 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

To reference the current DOM element in JavaScript, you can use this keyword within an event listener or use the event.target property to explicitly access the element that triggered the event.

1. Using this in Event Listeners

This keyword refers to the button element that triggered the click event, allowing direct manipulation of its style and content. The background color changes to yellow, and the text changes to "Clicked!" when the button is clicked.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
	<button id="btn1">Click Me (using this)</button>
	<script>
		document.getElementById('btn1').addEventListener('click', function () {
			this.style.backgroundColor = 'yellow'; 
			this.innerHTML = "Clicked!"; 
		});
	</script>
</body>
</html>

2. Using event.target Property

event.target refers to the button element that was clicked. Using this property, we apply a background color and update the text to "Clicked!" for the specific element that triggered the event.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
	<button id="btn2">Click Me (using event.target)</button>
	<script>
		document.getElementById('btn2').addEventListener('click', function (event) {
			event.target.style.backgroundColor = 'yellow'; 
			event.target.innerHTML = "Clicked!"; t
		});
	</script>
</body>
</html>

3. Inline Event Handlers

In inline event handlers, this refers to the element that triggered the event (in this case, the button). We pass this to a function (highlightButton()), which allows us to change the element’s style.

HTML
<!DOCTYPE html>
<html lang="en">
<body>
  <button onclick="highlightButton(this)">Click Me (inline handler)</button>
  <script>
    function highlightButton(element) {
      element.style.backgroundColor = 'yellow';
      element.innerHTML = "Clicked!"; 
    }
  </script>
</body>
</html>

Conclusion

Here are some methods :

  • Uses this to reference the DOM element in event listeners, allowing easy style and content changes.
  • Uses event.target for flexibility, especially when dealing with functions that need to access the element that triggered the event.
  • Inline event handlers directly reference the element that triggered the event, providing a simple approach for DOM manipulation.

Next Article

Similar Reads

Article Tags :
three90RightbarBannerImg
  翻译: