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

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

Optimizing CSS for printing with margins and overflow

After stumbling upon a helpful solution here, I wanted to print small cage cards in a neat format with some tweaks of my own. Currently, this is how it appears for me (Fiddle): /* CSS styles */ (styles modified here) * { -moz-box-sizing: border-b ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

The jQuery form submission functionality fails to execute properly in the presence of a callback function

I have been on the hunt for a solution to this problem, but unfortunately I haven't been able to find one. The issue at hand is that when using the jQuery Submit function with a button and a callback function defined, it doesn't seem to work. Her ...

Once the form has been submitted, proceed to open a new page following processing

Trying to remove an entry or offer from the database and then return to the page with all entries/offers. Attempted using Javascript, but it successfully deletes the item without redirecting to the overview page. Is this the correct approach with Javascri ...

Creating personalized headers for WebSocket in JavaScript

I am currently in search of a straightforward method to utilize WebSocket with custom headers for a web application, utilizing PHP as the backend and js+vuejs for the frontend. My application needs to establish a connection with a WebSocket server based o ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Main.js in Electron cannot find the NODE_ENV environment variable

Currently, I am in the process of developing an application which involves: React 16.4.0 Electron 2.0.2 Webpack 4.11.0 After successfully compiling and running the app using webpack (webpack dev server), my focus now shifts to showing only Chr ...

Alert: '[Vue warning]: Directive "in testing" could not be resolved.'

Currently, I am running unit tests within a Vue 2.0 application using PhantomJS, Karma, Mocha and Chai. Although the tests are passing successfully, I am encountering a warning message with each test indicating an issue like this: ERROR: '[Vue warn ...

Selecting a dropdown value dynamically after a form submission in ColdFusion using jQuery

I created a basic form with the use of an onload function to populate market values by default. However, I encountered an issue where after selecting a market value from the drop-down list and submitting the form, the selected value does not stay selected ...

Issue with mouseout gap in Microsoft Edge when using the <select> element

A noticeable gap appears in Microsoft Edge between the <select> menu and its options when expanding the menu, as shown here: https://i.stack.imgur.com/SprJ2.png This particular issue can cause problems with the mouseout event due to inconsistent be ...

What is the best way to convert string dot notation into a nested object structure?

Is there a way to convert a dot notation string such as 'a.b.c.d' into an Object? And if the Object referenced doesn't exist, can we automatically create an empty one? var str = 'a.b.c.d' var obj = {} // Now what? function dotTo ...

Disable automatic playback of HTML video

There is an HTML video with an image that loads initially and then disappears to play the video. I would like the image to always be visible until I click on it. Once clicked, the video should start playing. You can view the code on JSFiddle: http://jsf ...

Only two options available: validate and hide; no additional options necessary

Having some trouble understanding the logic behind a JavaScript script that is meant to display select options based on another select option. Any tips on how to hide unused options? For example: If TV is selected, only show options for device, tsignal, b ...

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

Bootstrap modal should be closed by using the back button in bootstrap

Currently, I am in the process of developing an angularjs application that utilizes a bootstrap modal feature. My goal is to have the modal close when the user presses the back button on their phone. I have disabled html5mode, so my URLs include the # sy ...

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

Is there an official IRC channel for YUI?

Although the yui3 documentation is quite helpful, it can also be beneficial to ask unconventional questions in order to discover the best practices. Are there any gatherings or meetups for all the talented yui developers out there? ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...