AgainMe AgainMe - 3 months ago 9
HTML Question

Get td class of clicked tr?

How can I get the class of td from clicked tr?

I've this structure:

<tr role="row" data-id="1" class="odd parent">
<td class="sorting_1">test</td>
<td>foo</td>
<td>3223232</td>
</tr>


I wrote this code:

$('#datatable > tbody > tr').click(function()


what I want to do is prevent to handle the code above if the user click on the
td
with class
sorting_1
. Each tr have a td with this class, so I need to check if the user have clicked on this td class, and prevent the code execution.

UPDATE

The code provided by @T.J. Crowder working good but, when I click on the
<td>
that have this class I cannot continue the code, that's correct. But I need to check if the td also contains
::before
, infact this will added when the html does not have sufficient space (responsive), the right structure in this case is:

<tr role="row" class="odd parent" data-id="1">
<td class="sorting_1">test</td>
::before
"test"
<td>foo</td>
<td>3223232</td>
</tr>

Answer

You can do that by telling the handler to ignore tds with that class:

$('#datatable > tbody > tr').on("click", "td:not(.sorting_1)", function(e) (
// -------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    // ...
});

(This covers both of the scenarios below, direct clicks as well as clicks on descendants of the td.)


Alternately, you can do that by examining the target property on the event object your handler receives:

$('#datatable > tbody > tr').click(function(e) (
    // -------------------------------------^
    if ($(e.target).hasClass("sorting_1")) {
        // Don't do it
        return;
    }
});

If the td may have other elements inside it (span, em, etc.), you can use closest to find out:

$('#datatable > tbody > tr').click(function(e) (
    // -------------------------------------^
    if ($(e.target).closest(".sorting_1").length) {
        // Don't do it
        return;
    }
});

Re your additional question:

is possible check also if the td have :before? 'cause the :before is added when there is no space available to fit the html content (responsive). So your code working, but if I click on the td that have the class and there is no :before I cannot see the content to be displayed. Is possible check :before existence on this td?

You can get that from getComputedStyle on modern browsers:

console.log(
  getComputedStyle($("#target")[0], "::before").content
);
#target::before {
  content: 'Life, the Universe, and Everything? '
}
<div id="target">42</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I don't think you can get it on older browsers that don't support getComputedStyle. Also, test on your target browsers to decide between :before (the old pseudo-class) and ::before (its newer name).