How to tell if an element was clicked using pure Javascript

8

How to tell 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 it using pure Javascript?

    
asked by anonymous 02.04.2014 / 02:23

4 answers

14

Like your selector with jQuery you can use querySelectorAll and go search all elements that are descendants of <li> and use a for loop to iterate them and tie an event handler to each one.

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 click handler (to detect the click event) on <li> directly. If you later want to know which descendant element of <li> that was clicked you 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>
})
    
02.04.2014 / 12:33
2
02.04.2014 / 12:30
2

If you get multiple div with document.getElementByTagName() , then you create a for to add to each element a click event with addEventListener() . The clicked element will be referenced to the this object, which 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>
    
18.09.2015 / 05:11
0

Another thing that solves and I believe 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 have helped. Good luck!

    
02.10.2015 / 21:18