Reputation: 888
I'm appending a span element with jQuery to a table divider (although this questions is more css/html).
Since I started using position absolute (which I need for my width attribute), it now appends to the next table divider along to the one that I want.
See below
$(document).ready(function() {
var var1 = 2
var element = $('td').filter(function() {
var holidayText = $(this).contents()[0].textContent.trim();
return parseInt(holidayText, 10) == var1;
});
var cell_width = element.width();
var2 = 3;
var width = var2 * cell_width;
add_html = element.append('</br><span class="spanclass" style="width: ' + width + 'px; position: absolute"></span>');
});
div.class1 {
position: relative;
}
table {
border: 1px solid navy;
width: 70%;
text-align: center;
}
table th {
text-align: center;
width: 100px;
height: 20px;
}
table td {
width: 100px;
height: 100px;
vertical-align: top;
text-align: right;
border: 1px solid #c6c6ec;
}
span.spanclass {
background-color: purple;
height: 14px;
display: inline-block;
padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="class1">
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
I thought that append put it inside the element... so I'm a little confused?
How do I fix this? Thanks
Upvotes: 0
Views: 62
Reputation: 53684
The td
's need position: relative;
, which will mean the span
is positioned relative to the td
, then the span
s need top
and left
value to position them in the td
div.class1 {
position: relative;
}
table {
border:1px solid navy;
width: 70%;
text-align: center;
}
table th {
text-align: center;
width:100px;
height:20px;
}
table td {
width: 100px;
height: 100px;
vertical-align: top;
text-align: right;
border: 1px solid #c6c6ec;
position: relative;
}
span.spanclass {
background-color: purple;
height: 14px;
display: inline-block;
padding: 2px;
top: 0; left: 0;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="class1">
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
</tbody>
</table>
</div>
<script>
$( document ).ready(function() {
var var1 = 2
var element = $('td').filter(function() {
var holidayText = $(this).contents()[0].textContent.trim();
return parseInt(holidayText, 10) == var1;
});
var cell_width = element.width();
var2 = 3;
var width = var2*cell_width;
add_html = element.append('</br><span class="spanclass" style="width: '+width+'px; position: absolute"></span>');
});
</script>
Upvotes: 2