-5
<h3>Shirts</h3>
<ul id='list'>
    <li>Biker Jacket</li>
    <li>Mens Shirt</li>
</ul>

I need to get console.log out the second li element. I tried the code below but I was only able to access the first li element

document.querySelector("li").onclick = () => {
    console.log("Biker Jacket");
};

5 Answers5

1

Use querySelectorAll[1] for the second one:

document.querySelector("li").onclick = () => {
    console.log("Biker Jacket");
};
document.querySelectorAll("li")[1].onclick = () => {
    console.log("Mens Shirt");
};
<h3>Shirts</h3>
<ul id='list'>
    <li>Biker Jacket</li>
    <li>Mens Shirt</li>
</ul>

And since this seems like you want to console.log the text content of the clicked list item, you could do this:

function showText(elem) {
  console.log(elem.innerText);
}
document.querySelectorAll("li").forEach(li => li.addEventListener("click", () => showText(li)));
<h3>Shirts</h3>
<ul id='list'>
  <li>Biker Jacket</li>
  <li>Mens Shirt</li>
</ul>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Just use the querySelectorAll() method instead and target the second li element like this:

document.querySelectorAll("#list li")[1].onclick = () => {
  console.log("Biker Jacket");
};
<h3>Shirts</h3>
<ul id='list'>
    <li>Biker Jacket</li>
    <li>Mens Shirt</li>
</ul>
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • I tried different iterations and locations for the [1], had no clue you could pass #list li through but it worked perfect. Much thanks – Dean Schwartz Feb 15 '19 at 21:54
0

You can pass the element using this onclick of the li and print its text using textContent

function a(e)
{
console.log(e.textContent)
}
<h3>Shirts</h3>
<ul id='list'>
    <li onclick="a(this)">Biker Jacket</li>
    <li onclick="a(this)">Mens Shirt</li>
</ul>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

You can use the :nth-child(x) pseudo selector to get the element at position x like this:

document.querySelector("ul#list > li:nth-child(2)").onclick = () => {
    console.log("Biker Jacket");
};
<h3>Shirts</h3>
<ul id='list'>
    <li>Biker Jacket</li>
    <li>Mens Shirt</li>
</ul>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

There are a few ways to select it:

const item = document.querySelector("ul>li:nth-child(2)")

or

const item = document.querySelectorAll('#list li')[1]

or if it's just the last thing of any list you need:

const items = document.querySelectorAll('#list li');
const item = items[items.length-1];

When you have your item selected add a click handler to it:

item.addEventListener('click', ()=>{
  console.log(this.innerText);
});
Matt Coady
  • 3,418
  • 5
  • 38
  • 63