What is the best way to retrieve the ids of child divs that are directly beneath a single parent div?

If I have a structure like the one below, I am looking to access each individual div inside its parent div and print its id using a for loop.

<div class=abc>
  <div id="parent">
    <div id="one">
       <div id=........</div>
       <div id=........</div>
    <div id="two">
       <div id=........</div>
       <div id=........</div>
    <div id="three">
       <div id=........</div>
       <div id=........</div>
    <div id="four">
       <div id=........</div>
       <div id=........</div>
    <div id="five">
       <div id=........</div>
       <div id=........</div>
    <div id="six">
       <div id=........</div>
       <div id=........</div>
    <div id="seven">
       <div id=........</div>
       <div id=........</div>
    <div id="eight">
       <div id=........</div>
       <div id=........</div>
  </div>
</div>

When trying to print (in Java), all nested div ids are also being printed. How can I retrieve only the ids of the eight main divs in one for-loop? I am automating a website using Selenium WebDriver and have attempted the following:

List<WebElement> eightDivs = driver.findElements(By.cssSelector("#abc div:nth-child(n)"));
     for(WebElement singleDiv : eightDivs)
      {
         System.out.println(singleDiv.getAttribute("id"));
      }

Answer №1

This special CSS selector:

#abc div:nth-child(n)

Is used to target all div elements that are the nth child of their parent within the element with the id of #abc. The space signifies a descendant relationship, allowing for any parent within #abc to be considered. In this case, every div should technically match the criteria since they are all the nth children of their respective parents (albeit not directly under #abc). As a result, no elements will actually be selected using this selector.

To make it work correctly, replace #abc with #parent, use the child selector > for direct children under #parent, and eliminate the unnecessary :nth-child(n) part:

List<WebElement> selectedDivs = driver.findElements(By.cssSelector("#parent > div"));

for (WebElement divElement : selectedDivs)
{
    System.out.println(divElement.getAttribute("id"));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stop the endless scrolling of the carousel and keep it fixed in place

I'm having trouble with disabling auto scrolling even though I've set bs-interval to "false". Here's my code snippet: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

Achieving permanent proxy settings in Firefox Webdriver: A step-by-step guide

As Geckodriver does not allow direct proxy settings, I will manually adjust it with the following code snippet: from selenium import webdriver myProxy = "xxxxxxxxx:yyyy" ip, port = myProxy.split(":") profile = webdriver.FirefoxProfile() profile.set_pref ...

In Java, any call to scanner.nextInt will be overlooked

I was given a homework assignment that requires me to create a program that generates a text with exactly 8 characters (adding spaces if necessary and removing characters if there are too many). The program should also insert up to 30 "#" characters betwee ...

Cancel an AJAX request without interfering with the subsequent request

When working with a number input and the "onChange" event, I have come across an issue with my ajax request. Upon aborting the request, it seems to have a negative impact on subsequent requests. If I send just one request without aborting, everything runs ...

What is the reason for JSoup's removal of element IDs?

Currently, I am utilizing JSoup to sanitize some HTML content that cannot be trusted. During the process, I came across an intriguing observation. If I use the following code snippet: String html = "<div id='foo'><script type='text ...

Transitioning the Background Image is a common design technique

After spending hours trying to figure out how to make my background "jumbotron" change images smoothly with a transition, I am still stuck. I have tried both internal scripts and JavaScript, but nothing seems to work. Is there any way to achieve this witho ...

Combining CSS and JavaScript to handle two events with a single onClick

Here is the code I've created: <a href="#" id="home" class="showLink" onclick="showHide('example');return false;"> <li class="buttons">home</li> </a> <a href="#" id="user" class="showLink" onclick="showHide(&a ...

Generating an excel spreadsheet containing Greek characters

Trying to include Greek characters in xls files has been a challenge for me. I've experimented with different headers to achieve this on the fly. First attempt: header("Content-Type: application/$file_type;charset=utf-8"); header("Content-Dispositio ...

How can I access an iframe in selenium that only has a src attribute?

I'm having trouble finding the popup window I need: <iframe frameborder="0" src="javascript:'&lt;html&gt;&lt;/html&gt;';" style="position: fixed; width: 583px; height: 441px; left: 374px; top: 158px; background-color: rgb ...

Is there a way to efficiently close a window that is running a for loop alongside a thread.sleep command?

I am working on a school project that involves creating a canvas to draw random circles. To accomplish this, I am using a for loop to continuously spawn circles. In order to prevent my computer from crashing, I implemented the Thread.sleep(20) method. Howe ...

When using the sendkeys function in Selenium with Java, it accurately identifies the location but fails to input the data

When using Selenium in Java, the sendkeys function seems to be unable to enter data and is instead only locating the exact location. Visit the website driver.findElement(By.cssSelector(".langCard.fixedCard.bounceAni>span")).click(); ...

Chrome browsers may sometimes experience issues with printing on the first attempt

I am facing an issue with printing HTML contents and images on a button click. The first time I try to print the page, the print preview is empty, but it works fine on the second attempt. Can someone please assist me in resolving this problem? The image s ...

Guide to adding an icon within an HTML `<input>` element

Is anyone able to help me successfully place my icon font inside the search input field? I've tried adjusting the margin and padding, but nothing seems to be working! If you have any insights or suggestions, please let me know. Your help is greatly a ...

ReactJS - Element not specified

I'm experiencing a specific issue with the component below related to the changeColor() function, which is triggering an error message: TypeError: Cannot set property 'color' of undefined This error seems to be isolated within this compo ...

Issues arise when attempting to manipulate the DOM with ng-view in AngularJS

Apologies for not providing the code due to its length. I have a simple application with a single module, controller, and ng-view/routProvider. In my controller, when I use console.log(angular.element('div').length), it correctly shows that ther ...

Having issues with jQuery's .fadeIn function not functioning properly

Currently, I'm developing a website and I am aiming to achieve a specific effect where a text fades in every time the webpage is opened. To achieve this, I have implemented the following code snippet: $(document).ready(function() { $('#title ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

Maintaining the placement of an element in a fixed position while adding a border

Currently, I am in the process of developing an interactive online picture framing tool. My aim is to allow users to customize an image by selecting different border, mount, and frame sizes. These customizations will be reflected in real-time by adding cor ...

Tips for centering text inside a div using a separator

During my side project, I decided to use the angular material divider but encountered issues with aligning the text correctly. https://i.stack.imgur.com/zg1mu.png The problem can be seen in the image provided - the text on the right side is not aligned b ...

css code for styling html elements

HTML: <link rel="stylesheet" type="text/css" href="styles.css"><table border="0" cellpadding="0" cellspacing="0" class="month"> <tr><th colspan="7" class="month">January 2017</th></tr> <tr><th class="mon">Mo ...