2

I am trying to replace a table with my own table using grease monkey. The page that has the table has 2 tables with the same class and no IDs.

I need to replace only the second table (with my own table) and do nothing to the first table. There is nothing that really makes the second table unique from the first table, so the only thing I can think of is trying to add a DIV around the second table, but cant figure it out.

Any ideas? Heres the page code:

<h3>Table 1</h3>
<table class="details" border="1" cellpadding="0" cellspacing="0">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr> 
</tbody></table>

<h3>Table 2</h3>
<table class="details" border="1">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr><tr>
<th>3</th>
<td>4</td>
</tr> 
</tbody></table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JB.
  • 893
  • 3
  • 16
  • 29

1 Answers1

0

You can use xpath to find the second tables, and do something with it. The xpath expression would be (//table[@class="details"])[2]. Below I added an example which uses (//pre)[1] instead, this will find the first code block on this page, I will hide it as an example. So this hides the page code from your question. (//pre)[2] will hide my script.

See Also here for a tutorial how to use xpath.

// ==UserScript==
// @name           so-test
// @namespace      test
// @include        http://stackoverflow.com/questions/4635696/use-greasemonkey-to-remove-table
// ==/UserScript==

// find first <pre> on this page 
var xpathResult = document.evaluate('(//pre)[1]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;

// now hide it :)
node.style.display='none';
wimh
  • 15,072
  • 6
  • 47
  • 98
  • 1
    Alternatively, use `document.getElementsByClassName('details').item(1)` – user123444555621 Jan 08 '11 at 21:28
  • How would I go about adding my table, before table 2? Also, there is a slight delay on the page before table 2 is removed, is there a way to remove it before the page loads with jquery? – JB. Jan 08 '11 at 22:59
  • @Josh: Since you've marked this question as answered, open a new question for the "add" bit. As for the delay, you will always have a small one with Greasemonkey, even if you use jQuery; it's a design limitation of GM. – Brock Adams Jan 08 '11 at 23:30
  • Thanks Brock. Moved: http://stackoverflow.com/questions/4636856/use-greasemonkey-to-add-html-before-table – JB. Jan 08 '11 at 23:53