JQuery: how to navigate a table row to retrieve cell data

I am trying to navigate the row of the table that was clicked to extract data from other parts of the row.

This is a snippet of the HTML line the button was clicked on:

<tr><td class=" sorting_1">Foobar</td>
    <td>Hello</td><td><a href="/some/path/abc.html">42</a></td>
    <td>0</td>
    <td><img src="/images/img.gif"></td>
    <td>7:44 AM</td>
    <td><ul><li><a href="/path2/read/3">Read it</a></li>
            <li><a class="booboo" href="#">Just do it</a></li>
        </ul></td>

The cell element that was clicked has the class "booboo".

I want to be able to select the following data:

  • identifier used in the url of the previous brother li (in the above example 3)
  • name in the first column (in the example above it is "Foobar")
  • URL of the anchor element in the 2nd cell (should be /some/path/abc.html in this example)

Can someone specify the functions needed to navigate the table row, preferably with a snippet showing how to select values ​​in the example snippet above?

+3
5

...

$("table a.booboo").click(function() {
    var $this = $(this);
    var tr = $this.closest("tr"); 

    // the id used in the url of the previous li a sibling
    var a = $this.closest("ul").find("li:first a").attr("href");
    a = a.substring(a.lastIndexOf("/") + 1);
    alert(a);

    // the name in the first column
    var b = tr.find("td:first").text();
    alert(b);

    // the url of the anchor elem in the 2nd cell
    var c = tr.find("td:eq(2) a").attr("href");
    alert(c);
});

jsFiddle

+5

"traversing" , :

  • parent, a, li.
  • prev li li.
  • parents (, .parents("tr:first")), . Gah! , closest. ( closest. ...)
  • find, (, row.find("td:first").text(), )

... attr, , href.

+2

a.booboo ?

<a class="booboo"
   data-id="3"
   data-name="Foobar"
   data-url="/some/path/abc.html">Just do it</a>

:

$('a.booboo').click(function() {
  var user = $(this).data()
  alert(user.id)
})

I think this is the best solution because it does not depend on the exact structure of your HTML code, and it is cleaner than the other solutions offered.

+2
source

If the html structure is fixed, you can use this:

$(".booboo").click(function(){
  var tr = this.parentNode.parentNode.parentNode.parentNode;
  var foobar = tr.cells[0].innerHTML;
  var url = tr.cells[2].firstChild.href;
  var id = this.parentNode.previousSibling.firstChild.href.match(/\d+$/)[0];
  // ...
});
+1
source
$(".booboo").click(function() {

  var a = $(this);
  var tr = a.closest("tr");

  var readItUrl = a.closest("li").prev().find("a").attr("href");
  var tdText = tr.find("td:first").text();
  var tr.find("td:eq(1) > a").attr("href");

});
+1
source

Source: https://habr.com/ru/post/1793635/


All Articles