Reputation: 5299
I create html tables,and I would like to add class by reffering to arr
and its content
When I set selector,I suffer 2 problems.
①$( "td:contains('2')" )
selector select like 2
,12
,22
・・・・ my desired result is to select only 2
② I prepared arr
and I would like to write more simply by using arr
.
My desired result is to add class of arr
cells.
Is it simple way to achieve it?
Thanks
const arr=[1,2,10,11,14]
$( "td:contains('1')" ).addClass('aqua')
$( "td:contains('2')" ).addClass('aqua')
$( "td:contains('10')" ).addClass('aqua')
$( "td:contains('11')" ).addClass('aqua')
$( "td:contains('14')" ).addClass('aqua')
td {
transition-duration: 0.5s;
border: solid black 1px;
cursor: pointer;
}
div {
padding: 5px;
}
table {
border-collapse: collapse;
}
.aqua {
background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
for (let w = 0; w < 10; w++) {
html += '<tr>';
for (let d = 0; d < 10; d++) {
i = i + 1;
html += '<td data-layer=0>' + '<div>' + i + '</div>' + '</td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
</script>
Upvotes: 0
Views: 30
Reputation: 371049
:contains
can't search for an exact match, it'll just search for if the element contains the text somewhere. If you want the text to match exactly, after selecting the elements, filter
them by whether their .text() === '2'
:
const arr = [1, 2, 10, 11, 14].map(String);
/*
const getExactMatch = text => function() { return $(this).text() === text };
$("td").filter(getExactMatch('1')).addClass('aqua');
$("td").filter(getExactMatch('2')).addClass('aqua');
or:
*/
$("td")
.filter(function() { return arr.includes($(this).text()); })
.addClass('aqua');
td {
transition-duration: 0.5s;
border: solid black 1px;
cursor: pointer;
}
div {
padding: 5px;
}
table {
border-collapse: collapse;
}
.aqua {
background-color: aqua;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=calendar></div>
<script>
let html = ''
html += '<table>';
let i = 0;
for (let w = 0; w < 10; w++) {
html += '<tr>';
for (let d = 0; d < 10; d++) {
i = i + 1;
html += '<td data-layer=0>' + '<div>' + i + '</div>' + '</td>'
}
html += '</tr>';
}
html += '</table>'
document.querySelector('#calendar').innerHTML = html;
</script>
Upvotes: 1