How to know if an element was clicked using pure Javascript

Asked

Viewed 17,179 times

8

How to know if a descendant of a <li> was clicked using pure Javascript.

<div id="list">
    <a href="#">one</a>
    <a href="#">two</a>
    <a href="#">three</a>    
</div>

Using Jquery would be:

$('#list a')

How to do using pure Javascript?

4 answers

15


Similar to your selector with jQuery you can use the querySelectorAll and fetch all the elements that are descended from <li> and use a for loop for loops and tie an Event Handler to each.

Example (live here):

var descendentes = document.querySelectorAll("#list a");
for (var i = 0; i < descendentes.length; i++) {
    descendentes[i].addEventListener("click", function (e) {
        alert('O elemento clicado foi o ' + this.innerHTML);
    })
}

Another option is to add a Handler click (to detect the click event) on the <li> directly. If you then want to know which descending element of <li> that was clicked can use event.target.

Example (live here):

var li = document.getElementById("list");
li.addEventListener("click", function(event) {
    console.log(event.target); // este é o elemento clicado
    alert('O elemento clicado foi o ' + e.target.innerHTML);

    // dentro desta função o "this" refere-se ao <li>
})

2

If you catch several div with document.getElementByTagName(), then you create a for to add to each element a click event with the addEventListener(). The clicked element will be referenced to the object this, which you will do the desired action.

Example:

 window.onload = function() {
	var divs = document.getElementsByTagName("div");
	
	for(var i=0; i<divs.length; i++) {
		divs[i].addEventListener("click", function() {
			this.style.backgroundColor = "#ccc";
			});
		}
	}
div { width:100px; height:100px; background-color:#C00; margin:10px; display:inline-block;}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>
  
</head>
  
<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

</html>

2

  • 3

    Robson, Welcome to Stackoverflow! Can you complete your answer with example code for this question? Just as the answer is unclear, in addition the link you joined goes to an English page which does not help those who do not speak English.

0

Another thing that solves and I believe that is simpler would be:

$("#list a").click(function(event){
     event.preventDefault(); //Essa linha vc coloca caso queira anular o evento do click da tag <a>;
     console.log("O elemento clicado foi: " + $(this).text();
});

I hope I helped. Good luck!

  • Actually the question was about - how to do this using pure Javascript, but this is still a good answer if the question was meant to be - how to do it using jQuery.

  • 1

    You’re right, I was immediately seeing and answering without regard to the rest of the question, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.