How can i see if an element is inside another element

Viewed 57

I am doing an automation script for a work project and I need to be as precise as possible with elements on the page and their positions. Bellow is part of the html of the page with an example of an issue I am facing.

<div _ngcontent-umj-c296="" class="ui inverted menu" style="border-bottom: 1px #444 solid; margin-bottom: 0;" xpath="1">
         <button _ngcontent-umj-c296="" type="button" id="logo" class="header item icheader" xpath="1">

I am trying to assert the button is inside the "inverted menu". It is crucial for my automation to make sure the button is not only displayed on the page, but also inside the menu. This is not the only element on that menu. It is also just a clickable button (action to take the user to the home page).

I have already defined the menu as:

IWebElement topFrame = driver.FindElement(By.CssSelector("div[class='ui inverted menu']"));

I also have an assert to confirm the menu is present on the page:

 Assert.IsTrue(topMenu.Displayed, "Top menu bar is not displayed");

Is this possible? Or is it only possible to see if the element is displayed on the page?

1 Answers

One option is to use the topFrame element to locate the button element

bool inMenu = topFrame.FindElements(By.ID("logo")).Count == 1;

Or use the parent element as part of the element path

bool inMenu = driver.FindElements(By.CssSelector("div[class='ui inverted menu'] > #logo").Count == 1;

To use the button to locate its parent element you can use Xpath

IWebElement buttonTopFrame = driver.FindElement(By.ID("logo"));
IWebElement topFrame = buttonTopFrame.FindElement(By.Xpath(".//.."));

bool inMenu = topFrame.GetAttribute("class").Equals("ui inverted menu");
Related