0

I wrote a program, and would like to do thing (CSS/JavaScript) in nested table, but I met some problem.

I’d like to show something in the odd tr element in tbody, which is:

<tr>
    <th>0</th>
    <th>Match Key</th>
    <th>Marketing</th>
</tr>

and

<tr>
    <th>1</th>
    <th>Match Key</th>
    <th>Marketing</th>
</tr>

in my program, but when I use JavaScript or CSS, it will apply to the child table.

How can I escape child table in JavaScript and CSS?

JsFiddle

0

4 Answers 4

1

If you want styling to apply to, say, a table-cell in #report, but not apply to a cell in a nested table, you can use this:

#report > tbody > tr > td{ /*some styles*/ }

the > character in the CSS selector is called the child selector

So, for example #reports > tbody > tr selects only a table-row that is a direct child of a tbody that is a direct child to #reports

Sign up to request clarification or add additional context in comments.

Comments

1

you would have to target the immediate child of the tbody with >

#report > tbody > tr:nth-child(odd) > th{
        background-color: #f00;
}

Jsfiddle

for jquery use the same selector as above to target the th

if you are using javascript add class 'top' to the top level <tr> and this should work: jsfiddle

var tb = document.getElementById('report').getElementsByTagName('tbody')[0];
var trs = tb.getElementsByTagName('tr');
var newtr = new Array();
var count = 0;
for(i = 0;i<trs.length;i++){
    if(trs[i].className == 'top'){
        newtr[count] = trs[i];
        count++;
    }

}
for(i=0;i<newtr.length;i++){
    console.log(i)
    if(i%2 == 0){
        for(k=0;k<newtr[i].getElementsByTagName('th').length;k++){
            newtr[i].getElementsByTagName('th')[k].style.background = 'red';
        }
    }
}

Comments

0

DEMO

#report > tbody > tr:nth-child(2n+1) > th{
        background-color: #f00;
}

1 Comment

How can I do it in Javascript with any action.
0

Here is the JavaScript Solution.

JavaScript

var tr = document.getElementsByTagName('tr'),
    totalTr = tr.length;

for(var i = 0; i <= totalTr; i++){
    if( i%2 === 0 ){
        tr[i].className = 'odd';
    }
}

HTML

<table width="500">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    <tr>
        <td>7</td>
        <td>8</td>
        <td>9</td>
    </tr>
    <tr>
        <td>10</td>
        <td>11</td>
        <td>12</td>
    </tr>
</table>

CSS

.odd{background:#e5e5e5;}

Fiddle Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.