I have HTML table with three rows and three cells for each row. Each cell has class name. I want to get the class name of each cell and write it to array.
HTML table:
<table>
<tr>
<td class="O-marker"></td>
<td class="O-marker"></td>
<td class="X-marker"></td>
</tr>
<tr>
<td class="X-marker"></td>
<td class="O-marker"></td>
<td class="X-marker"></td>
</tr>
<tr>
<td class="X-marker"></td>
<td class="O-marker"></td>
<td class="O-marker"></td>
</tr>
</table>
When the getBoard
function is called, then get all the class names of cells and write it to board
array.
function getBoard() {
var board = [];
return board;
}
I want to use jQuery and .each()
method to get the class name and push the first character into the array board
. Example. By the first character I mean (X or O).
Using vanilla JS:
function getBoard() {
var board = [];
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i += 1) {
board.push(tds[i].className[0]);
}
return board;
}
Or in jQuery:
function getBoard() {
var board = [];
$('td').each(function(){
board.push(this.className[0]);
});
return board;
}
Using jQuery:
function getBoard() {
var board = [];
$('.table td').each(function (index) {
board.push($(this).attr('class')[0]);
});
return board;
}
console.log(getBoard());
You can treat the string as an array (sort of?) and get the first character with [0]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.