How to count attribute which have same value in HTML with javascript?
I have following code of HTML,
<table>
<tr>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td colspan="2">one</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td colspan="2">two</td>
</tr>
<tr>
<td>content</td>
<td>content</td>
</tr>
<tr>
<td colspan="2">three</td>
</tr>
</table>
What I really want is to count the "colspan", and take the those contents from those table with JavaScript only, no jquery and mootool please. Thanks you.
I have got the answer for this, can we optimize to be shorter code or just simply the code?
var tds = document.getElementsByTagName( 'td' );
var colspanCount = 0;
var valuecount = 0;
for( i=0; i<tds.开发者_如何学Pythonlength; i++ ) {
myvalue = (tds[i].hasAttribute( 'colspan' ));
if (myvalue == true) {
valuecount += 1;
}
}
document.write('my value is ' + valuecount);
I think using jQuery would be best, but something like this should work:
var tablecols = document.getElementsByTagName("td");
for(var i in tablecols) {
if (tablecols[i].getAttribute('colspan') != undefined) {
alert(tablecols[i].innerHTML);
}
}
Please note that this is untested.
Well you should probably loop over the tags by doing something like document.getElementsByTagName("td") and then use the getAttribute method on each of those objects and see if it returns you a value for colspan..
Pseudo code:
tds=document.getElementsByTagName("td")
for i fom 0 to tds.length
if tds[i].getAttribute("colspan") is defined
//do smthing
Hope that helps..
var tds = document.getElementsByTagName( 'td' );
var colspanCount = 0;
for( i=0; i<tds.length; i++ ) {
colspanCount += tds[i].hasAttribute( 'colspan' ) ? parseInt( tds[i].getAttribute( 'colspan' )) : 0;
}
document.write( 'Count: ' + colspanCount );
Tested to work:
http://jsfiddle.net/kmfvu/
Myself, I'd just use jQuery.
You can cheap-out and treat it like string and use .split('colspan="2"')
then the length - 1 will be your answer.
精彩评论