Home > OS >  What is the best way to get/select clicked element (which called the function basically) in javascri
What is the best way to get/select clicked element (which called the function basically) in javascri

Time:11-28

What is the best way to get (like document.getElementbyId() or others) in javascript. In particular: The element has been clicked and called the function using onclick attribute but does not have an id.

CodePudding user response:

You can pass in the parameter this.

For example

<script>
    function foo(element){
        element.innerHTML="bar";
    }
</script>

<p onclick="foo(this)">this text will change to bar when clicked</p>

CodePudding user response:

There are quite a few ways to get elements. You can get them by ID, as you mentioned, but you can get them by tag name, class name, CSS selectors and HTML object collections.

You can read all about it here: https://www.w3schools.com/js/js_htmldom_elements.asp

Here's an example:

const element = document.getElementsByTagName("p");

This example returns a list of all elements with .

const x = document.getElementsByClassName("intro");
  • Related