简体   繁体   中英

Determine whether html table object in javascript has the <colgroup> or not?

I want to determine that whether any html table on the webpage has the tags present or not. If it not present , I want to insert the colgroup tag in the html. I have got the table object in the javascript but I dont find any way to solve this problem. Please help !!!

See http://jsfiddle.net/jv5yQ/

Just use .getElementsByTagName('colgroup') :

HTML:

<table id="t1">
    <tr>
        <td>1-1</td>
        <td>1-2</td>
    </tr>
    <tr>
        <td>2-1</td>
        <td>2-2</td>
    </tr>
</table>

<table id="t2">
    <colgroup style="background-color:#F00"></colgroup>
    <colgroup style="background-color:#00F"></colgroup>
    <tr>
        <td>1-1</td>
        <td>1-2</td>
    </tr>
    <tr>
        <td>2-1</td>
        <td>2-2</td>
    </tr>
</table>

JavaScript:

var ids=['t1','t2'];
for(var i=0;i<ids.length;i++){
    var el=document.getElementById(ids[i]),
        cond=el.getElementsByTagName('colgroup').length===0;
    if(cond){
        var col1=document.createElement('colgroup'),
            col2=col1.cloneNode(false);
        col1.style.background='#0f0';
        col2.style.background='#f0f';
        el.insertBefore(col2,el.firstChild);
        el.insertBefore(col1,el.firstChild);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM