Long story short I'm making a greasemonkey script. The pages I work on have this specific table with various values depending on the page.
<table class="billing dead">
<tbody>
<tr>
<th>Index:</th>
<td>Long alpha numeric value here</td>
</tr>
<tr>
<th>Status:</th>
<td class="status">This text is red to denote urgency.</td>
</tr>
</tbody>
</table><!-- end billing dead -->
What I need to do is change the text "Index:" to something else, whether it be a button or a link depending on the situation. I'm just having a hard time actually locating the item via Javascript.
Looking around I found this: How to Get Element By Class in JavaScript? which provided me with this code:
function replaceContentInContainer(matchClass,content)
{
var elems = document.getElementsByTagName('*'), i;
for (i in elems)
{
if((" " + elems[i].className + " ").indexOf(" " + matchClass + " ") > -1)
{
elems[i].innerHTML = content;
}
}
}
That replaces the whole table, however it's the closest question/answer to my situation; it's just not quite right. Once I've found the table with that method linked above, is there a way to access the elements of that specific table? I've tried arbitrarily changing
elems[i].innerHTML = content;
into
elems[i][0].innerHTML = content;
which quickly taught me that elems[i]
isn't a node of nodes. Is there an easy way to do what I'm looking for?
Is there more than one "billing" table? Is there only one "Index" per and is it always the first row?
The following, complete script shows how to change the HTML about any/all "Index" rows, including activating the resulting buttons. It uses jQuery, which will save you much time and effort.
See the base code in action at jsFiddle.
// ==UserScript==
// @name _Buttonize the Index cells
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==
//--- Find all the "Index" headers.
var indexHdrs = $("table.billing.dead th:contains(Index)");
//--- Wrap them all in a button, for example.
indexHdrs.each ( function () {
$(this).wrapInner ('<button class="myButton" />');
} );
/*--- Activate the buttons. In this case they just display matching
cell contents.
*/
$("table.billing.dead th button.myButton").click ( function () {
var jThis = $(this); //-- The button that was clicked.
var matchingCell = jThis.parent ().next ();
alert (matchingCell.text () );
} );
Note: To use this script on Chrome, install the Tampermonkey extension -- which you will want to do anyway, both for the extra features, and to surmount Chrome's pending restrictions on userscript installation.