Replace style with JS to multiple clases - javascript

How can i do this code work with multiple classes?
$("td.field_358").each(function() {
var td = document.getElementsByClassName('field_358');
for (i = 0; i < td.length; i++) {
if (td[i].innerHTML.indexOf('Yes') !== -1) {
td[i].style.backgroundColor = '#f7fef7';
} else if (td[i].innerHTML.indexOf('No') !== -1) {
td[i].style.backgroundColor = '#fbe8ea';
}
}
})
Actually i'm repeating the code for diferents classes, just replacing the class... field_358, field_123...etc.
Its possible to do something more handy like:
$("td.field_358", "td.field_359", "td.field_360").each(function() {
var td = document.getElementsByClassName('field_358', 'field_359', 'field_360');
});
I'm a JS Noob...

You may put all the css-classes you're interested in in an array and iterate over that. For each iteration you execute the code you've already got:
['field_358', 'field_359', 'field_360'].forEach(function (cssClass) {
var td = document.getElementsByClassName(cssClass);
for (i = 0; i < td.length; i++) {
if (td[i].innerHTML.indexOf('Yes') !== -1) {
td[i].style.backgroundColor = '#f7fef7';
} else if (td[i].innerHTML.indexOf('No') !== -1) {
td[i].style.backgroundColor = '#fbe8ea';
}
}
});
A working example may be found at https://jsfiddle.net/9sba06r4/3
Side note: You don't need jQuery for this task, just a more-or-less up-to-date browser.
Sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Here's a reusable function that allows you to pass an array of numbers representing the ids you wish to target, and also allows you to pass in strings representing the colors you wish to use for highlighting.
You simply define your arguments to the function and call it.
const ids = [1, 2, 3, 4];
const yesColor = '#37fef7';
const noColor = '#fbe8ea';
highlightTds(ids, yesColor, noColor);
function highlightTds(ids, yesColor, noColor) {
ids.map(id => {
const tds = document.querySelectorAll(`.field_${id}`);
for (const key of Object.keys(tds)) {
if (tds[key].innerHTML.indexOf('Yes')) {
tds[key].style.backgroundColor = yesColor;
} else if (tds[key].innerHTML.indexOf('No')) {
tds[key].style.backgroundColor = noColor;
}
}
});
}
<table>
<tr>
<td class="field_1">Yes</td>
</tr>
<tr>
<td class="field_2">No</td>
</tr>
<tr>
<td class="field_3">Yes</td>
</tr>
<tr>
<td class="field_4">No</td>
</tr>
<tr>
<td class="field_2">Yes</td>
</tr>
<tr>
<td class="field_1">No</td>
</tr>
</table>

Related

How to add a cell in html table and check for duplicates, without entering the following loop?

Hey guys I am trying to add a new cell in html table and while checking for duplicates in the table. I loop over the table to check for duplicates but I want this alert to only show if there is a duplicate or not? Right now the alert is looping with the each function? It's probably an easy task but I can't handle it. Can someone help me?
$("#btnCheck").on("click", function() {
let company_name = $("#test1").val();
$('#companyTable tr').each(function() {
$(this).find('td').each(function() {
if ($(this).text() === company_name) {
alert("duplicate found");
return false;
} else {
alert("duplicate NOT found");
return false;
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="companyTable">
<thead>
<tr>
<td>Company Name</td>
</tr>
</thead>
<tbody>
<tr>
<td>toyota</td>
</tr>
<tr>
<td>bmw</td>
</tr>
<tr>
<td>suzuki</td>
</tr>
</tbody>
</table>
<input type="text" id="test1" />
<input type="button" id="btnCheck" value="ADD" />
I'm not common to JQuery, but in casual JavaScript this should work :
document.querySelector("#btnCheck").onclick = () => {
const companyName = document.querySelector("#test1").value;
let found = false;
document.querySelectorAll("#companyTable td").forEach(cell => {
if(cell.innerText == companyName){
found = true
}
})
alert("duplicate "+(found ? "" : "NOT ")+" found");
}
You do not need to query rows then cells.
alerting at each cell isn't the right thing to do. You should (as above) store your result (=found), and at the end of the loop only use your result.
Note: Using forEach in this case doesn't seem the most efficient way. You should rather you a casual for loop in order to break it as soon as you find a match :
const cells = document.querySelectorAll("#companyTable td");
found = false;
for(let i = 0; i < cells.length; i++){
if(cells[i].innerText == companyName) {
found = true;
break; // Stop the loop
}
}
In JQuery I would use something like
$("#companyTable tr td:contains('"+textToSearch+"')")
This should return all TD objects inside TR rows of your TABLE id="companyTable" which contains "textToSearch"
Break early from the outer loop, and only alert if it's not found after the loop:
$("#btnCheck").on("click", function () {
let company_name = $("#test1").val();
let found = false;
$('#companyTable tr').each(function () {
$(this).find('td').each(function() {
if ($(this).text() === company_name) {
alert("duplicate found");
found = true;
return false;
}
});
if (found) {
// no need to search through other rows either
return false;
}
});
if (!found) {
alert("duplicate NOT found");
}
});

How to get class names of table tds and write it to an array using jQuery?

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].

for each table push to array

I'm a beginner with code,
I'm trying to run on this table and get the text from each .winner class and push it to an Array, so instead of getting:
["aa","aa","dd"]
I'm getting
["aaaadd","aaaadd","aaaadd"]
$(document).ready(function(){
var arr = [];
var winner = $('.winner').text() ;
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
console.log(arr);
});
HTML:
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">dd</td>
<td>cc</td>
<td>bb</td>
<td>aa</td>
</tr>
</table>
I guess something is wrong with my for loop
var arr = [];
$('table .winner').each(function () {
arr.push($(this).text());
})
Example
or version without class .winner
$('table').each(function () {
arr.push($(this).find('tr').eq(0).find('td').eq(1).text());
});
Example
$('table .winner') - returns 3 td's with class .winner
$(this).text() - get text from current element.
In your example $('.winner').text() returns text "aaaadd", then you get $('table').length (will be 3) and three times push the same text to arr
The sentence
var winner = $('.winner')
will give you an array of objects, so you need to loop each of them and call text() method for each one.
With this:
var winner = $('.winner').text();
You are getting a combined texts from all the td elements marked as winner (see docs here).
Then, for each table, to push this value to the array:
for ( i = 0; i < $('table').length ; i++ ) {
arr.push(winner);
}
This is actually not necessary.
What you want is probably:
var winners = $('.winner');
for (var i = 0; i < winners.length(); ++i) {
arr.push(winners.eq(i).text());
}

querySelectorAll() print textcontent of all nodes

this is the code i am using to get all text content from webpage. yet its not working and I do not know what i am doing wrong.
<tr style="color:#000000" class="odd">
<td style="padding:5px 5px 5px 10px" align="center"><input type="checkbox" name="cards[]" id="card_278002" value="278002"></td>
<td align="center">411756</td>
<td align="center">Sherrie</td>
<td align="center">89852</td>
</tr>
and thats my Js code :
function get42() {
return document.querySelectorAll('tr>td').textContent;
}
console.log(page.evaluate(get42));
Output : null .. what am I doing wrong ?
You can't use document.querySelectorAll like that. It returns a NodeList. You have to take the textContent from each Node yourself.
Longer way:
function get42() {
var tds = document.querySelectorAll('td'),
result = [];
for (var i = 0; i < tds.length; i++) {
result.push(tds[i].textContent);
}
return result;
}
Or Shorter:
function get42() {
var tds = document.querySelectorAll('td');
return Array.prototype.map.call(tds, function(t) { return t.textContent; });
}
js fiddle

Nested tag name with getElementsByTagName doesn't work

I have the following div that contains the table and its data queried from database
<div id="content">
<table>
<tbody>
<tr>
<th class="header" colspan="2">Food items include:</th>
</tr>
<tr>
<td id="15" class="fruits">Papaya+salt</td>
<td><p>This includes papaya and salt</p></td>
</tr>
<tr>
<td class="meat">Baked chicken</td>
<td><p>This includes a chicken thide and kethup</p></td>
</tr>
<tr>
<td id="1" class="Juices">Strawberry Sting</td>
<td><p>Sugar, color and water</p></td>
</tr>
<table>
</div>
That table is defined in a page.aspx
and here is my code used to sort that table data alphabetically
OldFunc = window.onload;
window.onload = OnLoad;
function OnLoad(){
try{
var pathName = window.location.pathname.toLowerCase();
if( pathName=="/Resources/Glossary.aspx") {
sort_it();
}
OldFunc();
}
catch(e) {
}
}
function TermDefinition(def_term,def_desc)
{
this.def_term=def_term;
this.def_desc=def_desc;
}
function sort_it()
{
var gloss_list=document.getElementsByTagName('td');
var desc_list=document.getElementsByTagName('td p');
var gloss_defs=[];
var list_length=gloss_list.length;
for(var i=0;i<list_length;i++)
{
gloss_defs[i]=new TermDefinition(gloss_list[i].firstChild.nodeValue,desc_list[i].firstChild.nodeValue);
}
gloss_defs.sort(function(a, b){
var termA=a.def_term.toLocaleUpperCase();
var termB=b.def_term.toLocaleUpperCase();
if (termA < termB)
return -1;
if (termA > termB)
return 1;
return 0;
})
for(var i=0;i<gloss_defs.length;i++)
{
gloss_list[i].firstChild.nodeValue=gloss_defs[i].def_term;
desc_list[i].firstChild.nodeValue=gloss_defs[i].def_desc;
}
}
Please lookat the the two getElementsByTagName, I think I am misuse its content since nothing is done on the output.
Invalid:
desc_list=document.getElementsByTagName('td p');
You can't pass a css selector to that function, only a tag name like div\ span input etc'.
You might want to use:
desc_list = $('td p');
Since you tagged the question with jQuery, or document.querySelectorAll for vanilla js:
desc_list = document.querySelectorAll('td p');

Categories

Resources