0

So, I m here trying to remove a first div inside a body tag, but unble to figure out how can we able to? there is no clear guidance how we can do that.

<!DOCTYPE html>
<html>
<body>
  <div>This div needs to hide</div>
</body>
</html>

XPATH: /html/body/div[1]

I had below the example which removes with the help of the ID attribute but, this can be done using the XPath. It would be great if someone guide me through.

<!DOCTYPE html>
<html>
<body>
<h1>The Element Object</h1>
<h2>The remove() Method</h2>

<p id="demo">Click "Remove", and this paragraph will be removed from the DOM.</p>
<button onclick="myFunction()">Remove</button>

<script>
function myFunction() {
  const element = document.getElementById("demo");
  element.remove();
}
</script>

</body>
</html>

**

Just because my question is closed I'm posting my answer in question for future consideration.

**

Update: credits to: here Chrome extension use to detect the xpath: here

Target

<!DOCTYPE html>
<html>
<body>
  <div class="alert alert-warning">Hide me baby!</div>
</body>
</html>

Finding and removing by XPath

function getElementByXpath(path) {
      return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
  
let x = getElementByXpath("/html/body/div[1]");
x.style.display = "none";

Finding and removing by class

document.getElementsByClassName('div.alert.alert-warning').style.display = "none";
2
  • Why doesn't your snippet demo have any div elements? Commented Sep 1, 2022 at 19:37
  • You can can get the node by using document.evaluate function. Once you are able to resolve it, you can then apply CSS styles to hide it or even remove it. This may help you. gist.github.com/rebecca321/56264748d80df2e1de99 Commented Sep 1, 2022 at 19:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.