How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to identify the label above the dropdown and then select the subsequent div element containing the dropdown.

The objective is to target the dropdown associated with a Label labeled "Title"

I experimented with various XPaths and attempted something like the following:

//span[text()='Title']/following-sibling::div[@class='col-xs-12 form-field input_controls ']

**Updated Code Here:

<div class="form-group is-required sc-row sc-row-12"><div id="label_IO:d027ec571b332450c82599361a4bcbb2" class="" nowrap="true" type="18" oncontextmenu="return contextQuestionLabel(event, 'd027ec571b332450c82599361a4bcbb2', '18');"><label for="IO:d027ec571b332450c82599361a4bcbb2" class="col-xs-12 control-label"><span id="status.IO:d027ec571b332450c82599361a4bcbb2" title="Mandatory - must be populated before Submit" mandatory="true" oclass="" class=" required-marker" data-original-title="Mandatory - must be populated before Submit">&nbsp;</span><img src="images/s.gifx" style="width:1px; margin-right:0px; margin-left:0px" id="section508.IO:d027ec571b332450c82599361a4bcbb2" alt="Mandatory - must be populated before Submit" title="Mandatory - must be populated before Submit" data-original-title="Mandatory - must be populated before Submit"><span class="sn-tooltip-basic " data-toggle="tooltip" data-placement="auto" title="Title" data-original-title="Title">Title</span></label></div><div class="col-xs-12 form-field input_controls "><select name="IO:d027ec571b332450c82599361a4bcbb2" id="IO:d027ec571b332450c82599361a4bcbb2" class="form-control cat_item_option " onchange="if (typeof(variableOnChange) == 'function') variableOnChange('IO:d027ec571b332450c82599361a4bcbb2')"><option value="" selected="SELECTED" role="option">-- None --</option><option value="b30330019f22120047a2d126c42e70ff" role="option">Chief Executive Officer</option><option value="f30330019f22120047a2d126c42e70ff" role="option">Chief Financial Officer</option><option value="370330019f22120047a2d126c42e70ff" role="option">Chief Technology Officer</option><option value="770330019f22120047a2d126c42e70ff" role="option">Director of Application Development</option><option value="b70330019f22120047a2d126c42e70ff" role="option">Director of Infrastructure</option><option value="f70330019f22120047a2d126c42e70ff" role="option">Director of Procurement</option><option value="3b0330019f22120047a2d126c42e70ff" role="option">Director of Security</option><option value="7b0330019f22120047a2d126c42e70ff" role="option">Director, Audit &amp; Risk</option><option value="bb0330019f22120047a2d126c42e70ff" role="option">Director, Finance Strategy</option><option value="fb0330019f22120047a2d126c42e70ff" role="option">HR Administrator</option><option value="3f0330019f22120047a2d126c42e70ff" role="option">HR Manager</option><option value="7f0330019f22120047a2d126c42e70ff" role="option">Infrastructure Analyst</option><option value="bf0330019f22120047a2d126c42e70ff" role="option">Procurement Administrator</option><option value="ff0330019f22120047a2d126c42e70ff" role="option">Recruitment Administrator</option><option value="330370019f22120047a2d126c42e7000" role="option">Recruitment Manager</option><option value="730370019f22120047a2d126c42e7000" role="option">Security Analyst</option><option value="b30370019f22120047a2d126c42e7000" role="option">Senior Auditor</option><option value="f30370019f22120047a2d126c42e7000" role="option">Senior Developer</option><option value="370370019f22120047a2d126c42e7000" role="option">Senior Finance Analyst</option><option value="770370019f22120047a2d126c42e7000" role="option">SVP, Human Resources</option></select><input type="HIDDEN" class="cat_item_option" name="sys_original.IO:d027ec571b332450c82599361a4bcbb2" id="sys_original.IO:d027ec571b332450c82599361a4bcbb2" value=""></div></div>

Answer №1

"To successfully access the dropdown menu, first identify the Label containing 'Title'"

In order to accomplish this task, utilize the following XPATH expression:

//span[text()='Title']//following::select[1]

The provided XPATH expression will pinpoint the initial <select> element that follows the node with the text 'Title'

Answer №2

It seems like using an XPath expression such as "../../div[2]/select" could help locate the select element, as explained in this helpful response.

Additionally, remember that the label ideally should contain a for attribute which can be utilized effectively.

const reference = document.querySelector("label");

const selectionByNavigation = reference.parentElement.parentElement.querySelector("select");
console.log("selectionByNavigation", selectionByNavigation);

const selectionByForAttribute = document.getElementById(reference.getAttribute("for"));
console.log("selectionByForAttribute", selectionByForAttribute);

function getElementUsingXpath(path, origin = document) {
  return document.evaluate(
    path,
    origin,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue;
}
const selectionByCustomXpath = getElementUsingXpath("../../div[2]/select", reference);
console.log("selectionByCustomXpath", selectionByCustomXpath);
<div>
  <div>
    <label for="unique-id">Pick a color</label>
  </div>
  <div>
    <select id="unique-id">
      <option>red</option>
      <option>blue</option>
    </select>
    <p id="similar-id"><i>lorem ipsum</i></p>
  </div>
</div>

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

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

What is the most efficient method of organizing form components together?

After exploring numerous tutorials, I have yet to discover the ideal solution for properly marking up a form that contains logical groupings of elements such as labels, controls (input or select), and previous values - essentially single fields. My prefer ...

Is there a copyright concern regarding CSS?

There are countless websites that spark my creativity. If I am inspired by a particular design, CSS, or JavaScript on one of these sites, am I allowed to copy it to my local folder and use it? For instance, let's say I come across a website called xy ...

What could be causing the occasional appearance of a tiny glitch, like a pixel dot, below a menu item when utilizing this hover effect?

Occasionally, a tiny dot appears almost imperceptibly, like the one below the "prices" menu item: https://i.stack.imgur.com/kyaP3.png This is the hover effect code I created: :root { box-sizing: border-box; } *, *::before, *::after { box-sizing: ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

When the jQuery document is ready, it typically returns null, but the console can still access and display

I have encountered an issue while working on a solution within a CMS (EPiServer). When I utilize console.log to check my object, it displays a null value. $(document).ready(function () { console.log("$('.EPiRequester').html() =" + $('. ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...

Issues with CSS Min-Height in Various Web Browsers

Lately, I've been working on a website and trying to create a border that surrounds all my content and extends the full length of the page. The #Container div is supposed to expand to fill the entire page. I've tried using min-height:100%; in my ...

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

python The program will not be terminated abruptly when calling selenium driver.quit()

The code snippet above is intended to terminate the program when an exception occurs by calling driver.quit(). However, despite this, the program continues to run. What did I miss here? try: driver.refresh() wait.until(ec.visibility_of_element_lo ...

An element seems to be missing on this webpage: Element not found: //button[@type='save'][text()='Accept All']

// I'm currently searching for an element on a webpage that will allow me to accept cookies. Error message: Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: //button[@type='save'][te ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Error: Execution time limit of 30 seconds has been surpassed, causing a fatal issue on line 64

I am attempting to style text retrieved from a SQL database, but when I try to preview it, I encounter a Fatal error: Maximum execution time of 30 seconds exceeded on line 64 . I tried setting the maximum execution time to 300 with `ini_set('max_execu ...

Transfer the data stored in the ts variable to a JavaScript file

Is it possible to utilize the content of a ts variable in a js file? I find myself at a loss realizing I am unsure of how to achieve this. Please provide any simple implementation suggestions if available. In my ts file, there is a printedOption that I w ...

modifying the arrangement of span elements

Currently, I am assisting a colleague in crafting articles for scientific journals. Interestingly, various publishers have distinct requirements regarding the format of cited authors in the bibliography. Some demand "last name, first name," while others pr ...

Well, it appears that I am having trouble establishing a connection between the users in this chatting application

I'm encountering a problem with establishing a connection between two users. I have already installed express and socket.io, but for some reason, the message is not getting through to the receiver's end. The code seems to be running fine as I can ...

Arrange a set of items using AngularJS according to specific criteria

Hello, I'm new to Angular I've created an angular app and you can view it in this plunkr. Can someone guide me on how to sort the list displayed here using angular? I want the course with the flag to always stay on top, while sorting the rest o ...

Unable to verify POST $http request using $httpBackend

Currently, I am in the process of writing unit tests to cover the http requests of my app. Using Jasmine and Karma, I have been following a tutorial on how to use $httpBackend from https://docs.angularjs.org/api/ngMock/service/. However, I encountered an e ...

Secure your application with Express.js and MySQL user authentication

Greetings everyone, I've been working on setting up a registration form using express.js and mysql. Unfortunately, it seems like my routes are not functioning correctly as they should. Even when all the required details are filled in correctly, the pr ...

Tips for updating the pagination layout in Material UI Table

Currently, I am attempting to modify the background color of the list that displays the number of rows in MUI TablePagination. <TablePagination style={{ color: "#b5b8c4", fontSize: "14px" }} classes={{selectIcon: ...