How do I get the content of a <td> using JavaScript?
My HTML
<tr class="g1">
<td 开发者_运维问答id="saveursqte_box[]">
<div class="t">
xxxxxxxxxxxxx
<div class="r">
<div class="a">
</div>
<img src="images/saveurs/saveur_test.jpg" width="125" border=0>
</div>
</div>
</td>
<td class="i">
<input type="text" name="saveursqte[]" alt="2.95" value="" size="3" onBlur="__sumform();">
</td>
</tr>
What I'm trying to do
I want to get the contents of: <td id="saveursqte_box[]">
using javascript.
which is:
<div class="t">
xxxxxxxxxxxxx
<div class="r">
<div class="a">
</div>
<img src="images/saveurs/saveur_test.jpg" width="125" border=0>
</div>
</div>
I tried this javascript:
var saveursqte_box = document.getElementsById('saveursqte_box[]');
and then
htmltotal = htmltotal + saveursqte_box[i].innerHTML;
but javascript doesn't seem to like me :-(
It is document.getElementById no "s".
This document.getElementById('saveursqte_box[]');
returns a single dom element not an array like jQuery.So the code to get the innerHTML would be:
htmltotal += saveursqte_box.innerHTML;
In addition to @scrappedcola's note about there being no 's' in getElementById
, you may also be having problems using square brackets in the element id.
I ran your example in Firefox 4 with <td id="saveursqte_box">
and it worked, whereas using <td id="saveursqte_box[]">
I got NULL
as the result of getElementById()
.
Also: saveursqte_box[i] i is not defined. Just use saveursqte_box
Thanks to all! I know my Javascript skills are low but by combining your answers together I came with this and it works perfectly :
htmltotal += document.getElementById('saveurmoisqte_box_' + i).innerHTML;
As per your answer, I removed the "s" of getElementById
. My bad: I copied getElementsByName
and then replaced the Name
by Id
... This is why there was a "s" there. The kind of mistake that can waste you a week to debug...
After that, I rename my <td id="extrasqte_box[]">
with <td id="extrasqte_box_0">
. I thought you could write ids
arrays like you do with names
(ex: name="xxxx[]"
) and then iterate but I was wrong.
With that in place it works perfectly! Not bea-u-tiful but it works.
What I'm actually doing with this is:
I have an order form with many items and when you fill an input (quantity), an hover image of the product appears to its right... and when you move away (onBLur), the form total is updated, AND using the function here above, I get the content of the <td>
(including the hover image) and put a summary of the items chosen in the "checkout section". The result is super-clean for the user and user-friendly. The inconvenient is I hope this makes sense to you.
精彩评论