Home > Software design >  How can I change the border color of a node from it's XPath?
How can I change the border color of a node from it's XPath?

Time:02-14

I have the XPath of an element (eg //html/body/div[1]/div[2]). I want to fetch the element and change it's border colour.

I can fetch the node using

document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue

But I can't figure out what to do next...

CodePudding user response:

You're not too far off from it -- Since you have the node from the code provided, you just have to assign add the styling. One way is by using JavaScript to add the in-line styles, for example:


// Select the node
var myDiv = document.evaluate('//html/body/div[1]/div[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;

//Add the style in-line
myDiv.style.border = "1px solid red";

// Or you can define a CSS class and add it that way
// myDiv.classList.add("my-class-with-border");

Working example: https://codepen.io/scarabaeus/pen/wvPqMPK

  • Related