So I have a page with a dynamically generate table that looks something like
<table id="enProps">
<tr>
<td class="en_US">
<input readonly="readonly" value="shipbillpayplacerequisition" type="text">
</td>
<td class="en_US">
<input class="longField" readonly="readonly" value="Ship, Bill & Pay : Place Requisition" type="txt">
</td>
<td style="display: none;" class="otherIds">
<input class="identifier" readonly="readonly" value="shipbillpayplacerequisition" type="text">
</td>
<td class="keyValue">
<input class="value longField" id="shipbillpayplacerequisition" value="" type="text">
</td>
</tr>
</table>
The number of rows can vary as can the what’s stored int eh value field of the input boxes. I’m trying to write a simple script in vanilla javascript (read: no external libraries such as JQuery) that compares the “value” values of two fields.
So far what I have is
var table = document.getElementById("enProps");
var rowCount = table.getElementsByTagName("TR").length;
var engValue;
var frenchValue;
for (var i = 0; i < rowCount; i++){
var row = table.rows[i];
var cellCount = row.cells.length;
for (var j = 0; j < cellCount; j++){
var cell = row.cells[j];
if (cell.getAttribute("class") == "en_US"){
var inputs = cell.getElementsByClassName("longField")[0].getAttribute("value");
}
}
}
Every time I try to run this get an error saying
cell.getElementsByClassName("longField")[0] is undefined
What’s odd is if I remove the getAttribute method call and print the value of inputs either with alert or console.log it shows the correct element. I’ve tried a number of variations including using .firstChild, .childNodes[0] and not stringing my method calls. Every single time I get an error saying either .getAttribute is not a function or that something is undefined and its always caused by the .getAttribute call on that line and what’s weirder is every single time calling console.log on my selector shows the appropriate input tag. So my question is why is .getAttribute erroring out when I trying to use it to get the value of the input tag’s “value” class?
It’s because your first
<td class="en_US">doesn’t have a nested element with the class"longField".You would need to make sure a match is found.
Or just call
getElementsByClassNamefrom thetrinstead.