Shaowei Ling
Shaowei Ling

Reputation: 186

How to select tags containing no some elements in nested tables?

There is the html code:

<body>
<table>
    <tr>
        <td>A</td>
        <td>
            <table>
                <tr>
                    <td>B</td>
                    <td>...</td>
                </tr>
            </table>
        </td>
    </tr>
    <tr>
        <td>C</td>
        <td>
            <table>
                <tr>
                    <td>D</td>
                    <td>...</td>
                </tr>
            </table>
        </td>
    </tr>
</table>
<button id="click">click</button>
</body>


What I want is get the text A and C in the above html code. In fact, I have tried some methods. My thought is to select td tag elements which do not have the descent tag element of table. However, I only can get these td elements with descent tag element of table, the jquery code is following.
You can try to run on jsddle.

$("#click").on("click", function () {
var ss = $("td:has(table)");
$.each(ss, function (index, value) {
        alert(index + $(this).html());
    });
});

Thanks for any help.

Upvotes: 1

Views: 93

Answers (3)

Shaowei Ling
Shaowei Ling

Reputation: 186

I also find another solution to the question, which may be more easily understood for a newbie as me. Though the html part does not show tag tbody, it exists indeed. I checked and displayed the body of table. Then to select the first td of each tr in the first table. The javascript code is following.

$("#click").on("click", function () {
  $("#message").text($("table").html());
  var trs = $("tbody:first > tr");
  $.each(trs, function (index, value) {
    var td = $(this).find("td:first");
    alert(td.text());
  });
});

Upvotes: 0

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this:

$("#click").on("click", function () {
    $("td").each(function(index){
        if(($(this).closest('table').parent('td').length == 0) && ($(this).find('table').length == 0))
           alert(index + $(this).html());
    });
});

DEMO

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

My thought is to select td tag elements which do not have the descent tag element of table.

Then use not selector:

$("#click").on("click", function () {
var ss = $("td:not(:has(table))");
$.each(ss, function (index, value) {
        alert(index + $(this).html());
    });
});

Upvotes: 0

Related Questions