First pass in javascript

I want to give each element in the table a generated identifier. See the html table below:

<table> <tbody> <tr> <td>A1</td> <td>A2</td> <td> <a href="#">A3</a> </td> </tr> <tr> <td>B1</td> <td>B2</td> <td> <a href="#">B3</a> </td> </tr> <tr> <td>C1</td> <td>C2</td> <td>C3</td> </tr> </tbody> </table> 

I want to give each element an identifier using width traversal. So, the result will look like this:

 <table> <tbody id="0"> <tr id="1"> <td id="4">A1</td> <td id="5">A2</td> <td id="6"> <a href="#" id="13">A3</a> </td> </tr> <tr id="2"> <td id="7">B1</td> <td id="8">B2</td> <td id="9"> <a href="#" id="14">B3</a> </td> </tr> <tr id="3"> <td id="10">C1</td> <td id="11">C2</td> <td id="12">C3</td> </tr> </tbody> </table> 

I tried using the each () function in jquery to generate an identifier for each element in this table, but the crawl algorithm used in each function () is a workaround.

Can anyone suggest me javascript code for this?

+4
source share
2 answers
 var n = 0 var level = $("table"); while (level.children().length) { level = level.children().each(function(_, el) { el.id = n++; }) } 

DEMO: http://jsfiddle.net/J5QMK/


If you want to avoid redundant .children() calls, you can do this:

 while ((level = level.children()).length) { level.each(function (_, el) { el.id = n++; }) } 

DEMO: http://jsfiddle.net/J5QMK/1/

+6
source

A common way to do a breadth-first search is to use a queue as follows:

 jQuery(document).ready(function () { var ctr = 0; var queue = []; queue.push(jQuery("table").children()); // enqueue while (queue.length > 0) { var children = queue.shift(); // dequeue children.each(function (ix, elem) { queue.push( // enqueue jQuery(elem).attr("id", ctr++).children(); ); console.log(elem.tagName + ": " + elem.id); }); } }); 
+4
source

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


All Articles