Issue
Using the following, if I click on either of the first two links in the list, the value of the ID is not written out via console.log. The same applies for the 3rd list item, which contains span tags rather than a hyperlink.
If I click to the right of the actual list item that contains HTML then the ID is written to the console:
var words = document.querySelectorAll('.words');
if (words.length) {
words.forEach(word => {
word.addEventListener('click', e => {
if (!e.target.id) return;
var id = e.target.id;
console.log("id: " + id);
});
});
}
<div class="words">
<ul>
<li id="daily.commitment"><a href="#">daily.commitment</a></li>
<li id="universe.fend"><a href="#">universe.fend</a></li>
<li id="trite.hog"><span>trite.hog in span</span></li>
</ul>
</div>
If the HTML in the list item is removed, then clicking on the actual text between the li
tags means the ID of the list item is written to the console as seen here:
var words = document.querySelectorAll('.words');
if (words.length) {
words.forEach(word => {
word.addEventListener('click', e => {
if (!e.target.id) return;
var id = e.target.id;
console.log("id: " + id);
});
});
}
<div class="words">
<ul>
<li id="daily.commitment">daily.commitment</li>
<li id="universe.fend">universe.fend</li>
<li id="trite.hog">trite.hog</li>
</ul>
</div>
What change do I need to make to the JS code so that the ID of the list item is picked up even if the list item contains HTML?
Solution
The fact that your element "contains HTML" is not a reason why the ID value isn't written to the console; it's that you're logically gating the console log output when event.target.id
doesn't exist. This is true when you have a click
event dispatched on one of your a
or span
elements, because they have not had an id
value defined.
A quick fix would be to properly add the event listener to each li
, then use event.currentTarget
to compare the ID of the element on which the event listener was added:
var words = document.querySelectorAll('.words ul li');
if (words.length) {
words.forEach(word => {
word.addEventListener('click', e => {
if (!e.currentTarget.id) return;
var id = e.currentTarget.id;
console.log("id: " + id);
});
});
}
<div class="words">
<ul>
<li id="daily.commitment"><a href="#">daily.commitment</a></li>
<li id="universe.fend"><a href="#">universe.fend</a></li>
<li id="trite.hog"><span>trite.hog in span</span></li>
</ul>
</div>
Answered By - esqew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.