I’m trying to get my head around Event’s and I’m totally lost? I would like to access an elements id from an event listener, using e.path
Array? The id that I want is always in the article id=”someID”
node of the objTmp Array()
.
I also can figure out why this only works in Chrome all other browsers say that objTmp
is undefined?
Any help would be appreciated…
JavaScript
x
66
66
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8" />
5
<title>Working </title>
6
7
<style type="text/css">
8
</style>
9
10
<script type="text/javascript">
11
12
function init() {
13
14
var eventTmp = document.querySelectorAll("ul li");
15
for (var i = 0; i < eventTmp.length; i++) {
16
eventTmp[i].addEventListener('click', function (e) {
17
var objTmp = e.path;
18
for (var i = 0; i < objTmp.length; i++) {
19
20
if (objTmp[i].tagName === "ARTICLE") {
21
//This is where I get lost
22
//How do I get the id from this node??
23
var x = objTmp[i];
24
console.log(x);
25
}
26
}
27
e.stopPropagation();
28
}, false);
29
30
}
31
}
32
33
</script>
34
</head>
35
<body onload="init()">
36
<main id="">
37
<article id="id_Article0">
38
<section>
39
<h2>Header</h2>
40
<div>
41
<ul>
42
<li>Link 1</li>
43
<li>Link 2</li>
44
<li>Link 3</li>
45
</ul>
46
</div>
47
</section>
48
</article>
49
<article id="id_Article1">
50
<section>
51
<h2>Header</h2>
52
<div>
53
<p>
54
<h3>Some Text</h3>
55
<ul>
56
<li>Link 1</li>
57
<li>Link 2</li>
58
<li>Link 3</li>
59
</ul>
60
</p>
61
</div>
62
</section>
63
</article>
64
</main>
65
</body>
66
</html>
Advertisement
Answer
Here’s a way to locate the ancestor ARTICLE node without using event.path:
JavaScript
1
21
21
1
function init() {
2
3
var eventTmp = document.querySelectorAll("ul li");
4
for (var i = 0; i < eventTmp.length; i++) {
5
eventTmp[i].addEventListener('click', function (e) {
6
var articleNode = this;
7
while (articleNode.nodeName != "ARTICLE" && articleNode.nodeName != "BODY") {
8
articleNode = articleNode.parentNode;
9
}
10
if (articleNode.nodeName == "BODY") {
11
// no article ancestor was found
12
} else {
13
// do something with articleNode
14
console.log(articleNode.id);
15
}
16
17
e.stopPropagation();
18
}, false);
19
}
20
}
21