Without using jQuery (because I have yet to even start that section yet), and just using some good old JavaScript/DOM, how could I select the last element of an item in a list.
For example I have the following HTML:
<section id="container">
<ul>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three</li>
</ul>
<ol>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three</li>
</ol>
</section>
Without using jQuery (because I have yet to even start that section yet), and just using some good old JavaScript/DOM, how could I select the last element of an item in a list.
For example I have the following HTML:
<section id="container">
<ul>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three</li>
</ul>
<ol>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three</li>
</ol>
</section>
And I want to select this item and return it in the DOM: <li class="third">three</li>
from the ol
list.
I understand that document.querySelector
only selects the first element in the document, which would be document.querySelector('li.third')
. How would I do the opposite and select the last?
-
1
Which list,
ol
orul
? – Mr. Polywhirl Commented Jan 7, 2020 at 14:07 - 'ol' is what I am aiming for @Mr.Polywhirl – user5617839 Commented Jan 7, 2020 at 14:08
-
1
#container ol li.third
? – Justinas Commented Jan 7, 2020 at 14:12 - li.third from the ol list @Justinas – user5617839 Commented Jan 7, 2020 at 14:12
3 Answers
Reset to default 4You can use *:last-child
if you have mixed child elements.
console.log(document.querySelector('#container *:last-child .third').textContent);
<section id="container">
<ul>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three</li>
</ul>
<ol>
<li class="first">one</li>
<li class="second">two</li>
<li class="third">three (here)</li>
</ol>
</section>
You can also grab the the last child by either:
#container *:last-child li:last-of-type
or#container *:last-child li:last-child
In order to get your item, you need to select properly.
This means you need to be specific when you want to select .third
Sequence to select #container
-> ol
-> (either li:last-child
or li.third
)
document.querySelector("#container > ol > li.third");
You can use document.querySelector('ol li:last-child')
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744886226a4599134.html
评论列表(0条)