I am trying to get last li element of list . but it is not giving correct output. here is my markup
<div class="abc">
<ul>
<li>1</li>
<ul><li>1.1</li><li>1.2</li></ul>
<li>2</li>
<ul><li>2.1</li><li>2.2</li></ul>
<li>3</li>
<ul><li>3.1</li><li>3.2</li></ul>
</ul>
</div>
trying like this
console.log(document.querySelector('.abc ul li:last-child').innerHTML)
output Element
<li>1.2</li>
Expected output
<li>3</li>
There are 2 problems
Your HTML Is invalid as ul is not a valid child of ul so the nested ones need to be actually inside a li
Use the > modifier to find direct descendents only in the selector
console.log(document.querySelector('.abc>ul>li:last-child').innerHTML)
<div class="abc">
<ul>
<li>
1
<ul>
<li>1.1</li>
<li>1.2</li>
</ul>
</li>
<li>
2
<ul>
<li>2.1</li>
<li>2.2</li>
</ul>
</li>
<li>
3
<ul>
<li>3.1</li>
<li>3.2</li>
</ul>
</li>
</ul>
</div>
If you do just want the text (and not the nested ul) you could put that text in a span and select that only
console.log(document.querySelector('.abc>ul>li:last-child span').innerHTML)
<div class="abc">
<ul>
<li>
<span>1</span>
<ul>
<li>1.1</li>
<li>1.2</li>
</ul>
</li>
<li>
<span>2</span>
<ul>
<li>2.1</li>
<li>2.2</li>
</ul>
</li>
<li>
<span>3</span>
<ul>
<li>3.1</li>
<li>3.2</li>
</ul>
</li>
</ul>
</div>
If you do just want the text (and not the nested ul) you could put that text in a span and select that only
You can just go for the javascript way like this.
li = document.querySelectorAll('.abc>ul>li');
console.log(li[li.length-1].innerText);
console.log(document.querySelector('.abc ul li:last-child').innerHTML)
This syntax of giving white space instead of adjacent selectors like ">" is used when we want to apply common styles to multiple class.
So replacing your whitespace with adjacent selectors like > will work in your case to select all its descendent childs.
console.log(document.querySelector('.abc>ul>li:last-child').innerHTML)
<div class="abc">
<ul>
<li>
1
<ul>
<li>1.1</li>
<li>1.2</li>
</ul>
</li>
<li>
2
<ul>
<li>2.1</li>
<li>2.2</li>
</ul>
</li>
<li>
3
<ul>
<li>3.1</li>
<li>3.2</li>
</ul>
</li>
</ul>
</div>