Search code examples
javascripthtmlcssqueryselector

How to retrieve the div first child element sibling node using querySelector?


I have the DOM structure like below

<div class="table_body">
   <div class="table_row">
      <div class="table_cell">first</div>
      <div class="table_cell">chocolate products</div><!-- want to access this div content -->
   </div>
   <div class="table_row">
      <div class="table_cell">third</div>
      <div class="table_cell">fourth</div>
   </div>
</div>

From the above HTML I want to access the div content of second div with classname table_cell inside first table_row div.

So basically I want to retrieve the content of div with classname table_cell with content chocolate products.

I have tried to do it like below

const element = document.querySelector('.rdt_TableBody');
const element1 = element.querySelectorAll('.rdt_TableRow')[0]
const element2 = element1.querySelectorAll('.rdt_TableCell')[0].innerHTML;

When I log element2 value it gives some strange output and not the text "chocolate products"

Could someone help me how to fix this. Thanks.


Solution

  • You can use:

    • the :nth-of-type pseudo-selector
    • combined with the immediate-child selector (>)

    Example:

    const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
    

    Working Example:

    const selectedDiv = document.querySelector('.table_body > div:nth-of-type(1) > div:nth-of-type(2)');
    
    selectedDiv.style.color = 'white';
    selectedDiv.style.backgroundColor = 'red';
    <div class="table_body">
        <div class="table_row">
            <div class="table_cell">first</div>
            <div class="table_cell">chocolate products</div> //want to access this div content
        </div>
        <div class="table_row">
            <div class="table_cell">third</div>
            <div class="table_cell">fourth</div>
        </div>
    </div>