Tuesday, March 07, 2023

Remove web page elements that match a certain xpath

Taking for example a bitbucket pull requests page and assuming that we want to hide all PRs tat contain the string JIRA-80 just copy and paste the below to the browser console and press enter
// 1. define the text string to search for as content of a tag
// 2. define the xpath string that matches the tr that contains a td that contains 5 nested divs that contain an anchor with tagContent 
// 3. define the xpath result object that contains all the ORDERED_NODE_SNAPSHOT_TYPE nodes that match the xpath string 
// 4. iterate the xpath result to hide each node in it
var tagContent='JIRA-80';
var xpath="//tr[td[div[div[div[div[div/a[contains(text(),'" + tagContent + "')]]]]]]]";
var xpathResult = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < xpathResult.snapshotLength; i++) {
  const xpathNode = xpathResult.snapshotItem(i);
  xpathNode.style.display = 'none';
}
Obviously you can inspect the element you want to remove and select the "delete element" option from the chrome inspector "elements tab" but automating the deletion of the elements that you do not want by knowing the xpath of them saves lots of time.

Followers