Getting the inner element of a particular child from the parent div using selenium with javascript

<div class="A">
  <svg> ... </svg>
  <button> 
    <svg> ... </svg>
  </button>
  <svg> ... </svg>
</div>
<div class="A">
  <svg> ... </svg>
  <button> 
    <svg> ... </svg>
  </button>
  <svg> ... </svg>
</div>

I'm facing a challenge in extracting the svg element within the button tag of the second div. Any assistance with this would be greatly appreciated.

Answer №1

To locate the svg element within a button inside a div using xpath, specify svg as the element's name:

This will target the second svg element that is a child of a button element within a div.

(//div/button/*[name()='svg'])[2]

Alternatively, if you are utilizing CSS, you can utilize the following selector:

This will select the div as the second child and then find the svg element within a button.

   div:nth-child(2)>button>svg

Answer №2

Give this xpath a try:

(//div/button)[2]/*[name()='svg']

Make sure to use parentheses so that you are selecting the second occurrence of //div/button on the current page.

For further information, refer to this answer:

Answer №3

If you're looking to select specific elements in your HTML document, consider using the querySelectorAll method.

// Use querySelectorAll to find all DIVs with class 'a'
const allDivsWithClassA = document.querySelectorAll(".a");
// Access the second element
const secondDiv = [...allDivsWithClassA][1];
// Find the svg wrapped by a button within this div
const svgWrappedByButton = secondDiv.querySelector("button > svg");

console.log(svgWrappedByButton);
<div class="a">
  <svg></svg>
  <button> 
    <svg></svg>
  </button>
  <svg></svg>
</div>
<div class="a">
  <svg></svg>
  <button> 
    <svg></svg>
  </button>
  <svg></svg>
</div>

Answer №4

If you want to target the second div, you will need to assign it an ID. The style will remain consistent through a class, but having the ID will simplify accessing the element. Here is one way to achieve this:

function fetchSVG(){
  // Assuming you have given the second div an ID of 'myID'
  var parentDiv = document.querySelector("#myID");
  var svgElements = parentDiv.querySelectorAll("svg");
  console.log(svgElements);
}

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

Generating personalized MongoDB collections for individual users - A step-by-step guide

My query is more about the procedure rather than a specific coding issue. I am working on a node application and using DHTMLX calendar. What I aim for is to have each user with their own set of events on their individual calendar. Currently, the implement ...

Discover how to extract the value from the server side during document.ready using jQuery without the need for any specific event

In my project, I'm facing a requirement where I need to fetch a value from server-side code using any event and utilize it to create a dialog box. Initially, I attempted to retrieve the value in window.onload but discovered that window.onload is trigg ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Transferring data between various stages of the user interface

As a newcomer to angularJs, I find myself facing an issue with two forms existing in different UI states (URLs) labeled as Step 1 and Step 2. The process requires filling up Step 1 and moving to the next step by clicking the NEXT button, which then leads t ...

Swap out the %20, which signifies a space in the iron router context

I am attempting to substitute the %20, which signifies a space in the URL, with a different character. Router.map(function () { this.route('promos', { path: '/:promo_name', waitOn: function(){ return Meteor.subscribe( ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

Having trouble retrieving a value within the jQuery.ajax success function

I need to implement jQuery Validator in order to validate if a user's desired username is available during the sign-up process. The PHP script untaken.php is responsible for checking this, returning either ok if the username is free or taken if it is ...

Navigating through various Headers in ReactjsHandling different Headers in Reactjs

I am currently working on a project using Reactjs (Nextjs) and I need to have different headers for the home page compared to the rest of the pages. I have created a "Layout.js" file where I have placed the header and footer components, and then imported ...

Add the appropriate ordinal suffixes ('-st', '-nd', '-rd', '-th') to each item based on its index

Imagine having an array filled with various option values, such as: var options = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grapefruit", "honeydew", "kiwi", "lemon", "mango", "nectarine", "orange", "pear", "quince", "raspberry", "strawbe ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Bring in JavaScript files on a global scale in Vue.js 3

Hello, I am facing an issue while trying to import jQuery and THREEJS globally into my Vue.js cli project. Whenever I attempt to import them into my .vue file (like home.vue), I encounter the following error: 'import' and 'export' ma ...

transform JSON data into XML format with the help of JavaScript

I need help converting a JSON object to an XML String and I'm struggling to find the right method. I recently came across a jQuery plugin called json2xml on https://gist.github.com/c4milo/3738875 but unfortunately, it does not properly escape the data ...

NodeJS Request Body Not Populated

Currently operating with node using [email protected] and [email protected]. Within my jade page, there exists a property like this: input(type='text',class='form-control', placeholder="Username", name='username', ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

Strategies for removing duplicate items from an array of objects

My array consists of objects with the following structure: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', 'de ...

Do you have any tips for conducting a Selenium test to verify the existence of a website?

I am in need of some guidance with running a test to verify that a website can be accessed from the internet. I have put together this code, but I suspect it may be incorrect. Any suggestions or advice would be greatly appreciated. Thank you! va ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

Initiate the Bull Queue Process upon launching the Application

As I develop my API, I am setting up a queue and adding jobs to it. Additionally, I have configured the API to start processing these jobs as soon as they are added. const newQueue = createQueue(queueName, opts); newQueue.add('JokesJob', data, o ...

When the number of selected students exceeds zero, activate the collapsing feature in React

When the number of students exceeds zero, the collapse should automatically open and the text in Typography (viewStudentList) will display 'Close'. On the other hand, if the student count is zero, the collapse should be closed and the text on Typ ...