Reputation: 160
I'm about to write an extension for Google Chrome Browser. It's a content script which changes the width of a table. This is the XPath for the mentioned table:
/html/body/table/tbody/tr/td/table[2]/tbody/tr/td[3]
/html/body/table/tbody/tr/td/table[2]/tbody/tr/td[3]/fieldset/div[1]/div[2]
/html/body/table/tbody/tr/td/table[2]/tbody/tr/td[3]/fieldset/div[2]/div[2]
/html/body/table/tbody/tr/td/table[2]/tbody/tr/td[3]/fieldset/div[3]/div[2]
Unfortunately, it's not possible to access the table with getElementById, getElementsByName or similar. I found the following solution:
document.getElement("body").childNodes[7].childNodes[1].childNodes[0].childNodes[3].childNodes[9].childNodes[1].childNodes[0].childNodes[5].width=500
document.getElement("body").childNodes[7].childNodes[1].childNodes[0].childNodes[3].childNodes[9].childNodes[1].childNodes[0].childNodes[5].childNodes[3].childNodes[3].childNodes[3].style.width="300px"
document.getElement("body").childNodes[7].childNodes[1].childNodes[0].childNodes[3].childNodes[9].childNodes[1].childNodes[0].childNodes[5].childNodes[3].childNodes[7].childNodes[3].style.width="300px"
document.getElement("body").childNodes[7].childNodes[1].childNodes[0].childNodes[3].childNodes[9].childNodes[1].childNodes[0].childNodes[5].childNodes[3].childNodes[5].childNodes[3].style.width="350px"
Although this solution works, I'm not satisfied with it. Is there a smarter way to do that?
Upvotes: 1
Views: 401
Reputation: 61952
Chrome supports the document.evaluate
function which can select elements by XPath.
The signature:
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result
);
In your case this will be
var expr = "/html/body/table/tbody/tr/td/table[2]/tbody/tr/td[3]";
var td = document.evaluate(expr, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
You can also use XPathResult.UNORDERED_NODE_ITERATOR_TYPE
to get a list of nodes through an iterator.
Edit: You can also use the transform the XPath to a CSS3 selector and use document.querySelector
:
var expr = "body > table > tbody > tr > td > table:nth-of-type(2) > tbody > tr > td:nth-of-type(3)";
var td = document.querySelector(expr);
Upvotes: 1