ex: given a facilities portion in a page, and it contains different facilities available in different ul in a column fashion.(so like column 1's ul contains various facilities in list item(li) form). so i want to access 2nd ul (imagine second column of a table) and its 4th and 5th list-items(li) only.
if I do this, document.querySelector(".text-body li") then I will get data from 1st ul only, but I want it from the second one.
here .text-body is the class and its same for every list.
<div class="text-block hospital-facility" id="section-facilities">
<h2 class="text-block-title"></h2>
<div class="facility-list"›
<h4 class="text-block-list-title">Comfort During Stay</h4>
<div class="text-body add-view-more" data-visible-item="6" data-
showmore-text="More Details">
<ul>...</ul>
<p class="text-right vm-wrp"></p> </div> </div>
<div class="facility-list>
<h4 class="text-block-list-title">Money Matters</h4>
<div class="text-body">
<u1>
<li>Health insurance coordination</li>
<li>Medical travel insurance</li>
<li>Foreign currency exchange</li>
<li>ATM</li> <li>Credit Card< li>
</ul>
in the above code, the second ul contains various payment methods , I need all of them. we can do ul:last-child but there are around 6-7 ul tags so we need to have something that will select only 2nd ul
So I suppose your html looks something like this:
<div id="ulParent">
<ul>
<li>li11</li>
<li>li12</li>
</ul>
<ul>
<li>li21</li>
<li>li22</li>
</ul>
</div>
Then you can do:
var secondUl = document.querySelector("#ulParent ul:nth-child(2)");
var fourthLi = secondUl.querySelector("li:nth-child(4)");
var fifthLi = secondUl.querySelector("li:nth-child(5)");
Update after OP added HTML example:
So with the following HTML:
<div class="text-block hospital-facility" id="section-facilities">
<h2 class="text-block-title"></h2>
<div class="facility-list">
<h4 class="text-block-list-title">Comfort During Stay</h4>
<div class="text-body add-view-more" data-visible-item="6" data-showmore-text="More Details">
<ul><li>...</li></ul>
<p class="text-right vm-wrp"></p>
</div>
</div>
<div class="facility-list">
<h4 class="text-block-list-title">Money Matters</h4>
<div class="text-body">
<ul>
<li>Health insurance coordination</li>
<li>Medical travel insurance</li>
<li>Foreign currency exchange</li>
<li>ATM</li>
<li>Credit Card</li>
</ul>
</div>
</div>
</div>
The ul is not the 2nd child of its parent so you can't use :nth-child(2).
Instead you need the 1st ul of the 2nd .facility-list:
var targetUl = document.querySelector("#section-facilities .facility-list:nth-of-type(2) ul");
// then retrieve the `li`s as the previous example shows:
var fourthLi = targetUl.querySelector("li:nth-child(4)");
var fifthLi = targetUl.querySelector("li:nth-child(5)");
Note that you can also get your targetUl using xpath:
var targetUl = $x("//h4[contains(text(), 'Money Matters')]//following-sibling::div//ul");