Is it possible to nest elements inside tables elements with a simple JavaScript/jQuery function? For example, each square has a unique ID (A1, B7, C5). Using that ID how could I place the checker image in any given tile when the tile is clicked?
Asked
Active
Viewed 44 times
0
-
You should provide some code you've tried. – Jordan Soltman Dec 01 '15 at 20:34
-
I've really just been searching the internet for a line of code like TableDivId.add(element). I haven't written anything down because I'm just looking for an existing function that will do this. @JordanS – Alex Brigham Dec 01 '15 at 20:37
-
1Your answer is: Yes. You can do that. – teynon Dec 01 '15 at 20:38
-
Great, I thought so! Could you provide an example? @Tom – Alex Brigham Dec 01 '15 at 20:39
-
`$("#A1").append($(""));` – teynon Dec 01 '15 at 20:39
-
You might want to peruse the [jQuery Manipulation functions](https://api.jquery.com/category/manipulation/). – Stryner Dec 01 '15 at 20:40
-
@Tom That worked great, thank you! – Alex Brigham Dec 01 '15 at 20:41
-
@Stryner I will take a look! – Alex Brigham Dec 01 '15 at 20:41
-
Possible duplicate of [Creating a div element in jQuery](http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery) – teynon Dec 01 '15 at 20:43
1 Answers
0
$('table').on('click', 'td', function() {
$(this).toggleClass('check');
var col = $(this).prevAll('td').length;
var row = $(this).parent().prevAll('tr').length;
console.log(row + ' ' + col);
});
table tr {
background-color: red;
}
table tr:nth-child(2n) td:nth-child(2n+1),
table tr:nth-child(2n+1) td:nth-child(2n) {
background-color: black
}
table td {
width: 50px;
height: 50px;
}
table td.check:before {
content: '';
display: block;
width: 40px;
height: 40px;
margin-left: 5px;
margin-top: 5px;
background-image: url('https://lh4.ggpht.com/Vp9KgW5XXVC31JPh_LmB6KQDK6OK-dwawspREgTx4Jo1EshyaIU_HTB_Dw1fK57bB84=w300');
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>
</table>

Robert McKee
- 21,305
- 1
- 43
- 57