I have sample code as follows :
<table id='emailTable'>
<tr id='tablecontent'>
<td>
</td>
<td>
<a ....>delete</a>
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
<a ....>delete</a>
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
</td>
</tr>
<table>
Here, I want to delete the row onclick of delete link with the next row.
Have tried with 'parentNode' and removechild with currentNode but nothing happens.
you can attach an event listener to a for click event and use $(this).parents('tr') inside event handler to access parent row. something like this:
$('a').on('click', function(e){
e.preventDefault();
$(this).parents('tr').remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='emailTable'>
<tr id='tablecontent'>
<td>
</td>
<td>
delete
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
delete
</td>
</tr>
<tr id='tablecontent'>
<td>
</td>
<td>
</td>
</tr>
<table>
Here you go table row removal using JavaScript:
// get all rows
var rows = document
.querySelectorAll("#emailTable tr#tablecontent");
// create a find parent function
// since JavaScript do not have $(elem).parent("tr")
// which automatically search a parent or parent of parents that is a <tr>
var findParent = function (node, tagName)
{
var recursiveSearch = function(node, tagName)
{
// you can change the condition as you see fit.
return node.parentNode.tagName.toLowerCase() == tagName.toLowerCase() ? node.parentNode : recursiveSearch(node.parentNode, tagName);
};
// do a recursive search based from passed node if it matches with a given tag name.
return recursiveSearch(node, tagName);
};
// loop through each row
rows.forEach(function (item)
{
// find the delete element
var deleteElem = item.querySelector("td a.delete");
// if there is an delete element
if (deleteElem)
{
// add event listener
deleteElem.addEventListener("click", function ()
{
// find parent element that is a <tr>
var row = findParent(this, "tr");
// remove the row
row.remove();
});
}
});
working fiddle
hope that helps
Related
I am trying to change the color of the selected row from a table on a onmousedown event and reset all others (or keep them the same) . Only one row can be red at a time while all others are green.
What I have tried:
function HighLight(id) {
var rows = $('#tbl > tbody > tr').each(function(elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(e)">
<td>
v3
</td>
</tr>
</table>
Ideally I would like to store the old selected row so that I won't reset all others at each new selection, but in case I can't reset all would do it.
P.S I need to make due with the id that i am provided.I am using interop so the id is coming from the exterior. All my tr have that method injected in them.
The function name is wrong its Highlight not HighLight
To pass the id of the element on function call you cannot just pass any variable(e in your case). Use this.getAttribute('id') to get the id.
In the each() the argument elem represented the index of the element and not the element itself. Introduce another argument for index.
function Highlight(id) {
var rows = $('#tbl > tbody > tr').each(function(i,elem) {
elem.style.background = 'green';
})
var tr = document.getElementById(id);
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this.getAttribute('id'))">
<td>
v3
</td>
</tr>
</table>
Here is a quick example on how can you do that.
$("table tr").on('click', function(){
$(".highlighted").removeClass("highlighted");
$(this).addClass("highlighted");
});
table tr {
background: green;
}
table tr.highlighted {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Here is how it works:
It binds a click event to every row in the table (tr),
Every time you click on a row, all elements that has a class called highlighted loose it and the row that you clicked gets the class highlighted,
In css you can change the default background color for all rows and the color after highlighting.
If you don't want to use a css, here is similar function but instead of adding and removing class it does the same with the inline css property.
$("table tr").on('click', function(){
$("table tr").css("background", "green");
$(this).css("background", "red");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background: green;">
<td>
v1
</td>
</tr>
<tr id="tr2" style="background: green;">
<td>
v2
</td>
</tr>
<tr id="tr3" style="background: green;">
<td>
v3
</td>
</tr>
</table>
But I do not recommend the second solution.
You can have two css classes; one for selected row and other for remaining rows.
On click of the row, you can add the "selected" class to that row.
$("#tbl tr").click(function(){
var $this = $(this);
//remove the previous row selection, if any
$("#tbl tr.selected").removeClass("selected");
//add selected class to the current row
$this.addClass("selected");
});
#tbl tr{
background-color: aquamarine;
}
#tbl tr.selected{
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2" >
<td>
v2
</td>
</tr>
<tr id="tr3" >
<td>
v3
</td>
</tr>
</table>
You can do like this.by using class you can carry out other operations
$("#tbl").on("click", "tr", function() {
$(' tr').removeClass("Red")
$(this).addClass("Red")
});
.Red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1">
<td>
v1
</td>
</tr>
<tr id="tr2">
<td>
v2
</td>
</tr>
<tr id="tr3">
<td>
v3
</td>
</tr>
</table>
Several issues:
JS is case sensitive, so Highlight and HighLight (capital L) is not the same. I renamed the HighLight function to Highlight (lowercase l)
Use parameter this on function call in event handler attribute. This hands over the HTML element of the event handler attribute over to the event handler function (Highlight in your case)
Callback function of jQuery's each method has the index as a first parameter and the element as second
This makes your code work
function Highlight(tr) {
var rows = $('#tbl > tbody > tr').each(function(index, elem) {
elem.style.backgroundColor = 'green';
})
tr.style.background = 'red';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbl">
<tr id="tr1" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr id="tr2" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr id="tr3" style="background-color:aquamarine" onmousedown="Highlight(this)">
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>
There are some more things you can do to enhance your code
Don't use style in your JS code, but set classes for CSS
Don't use HTML onmousedown attributes, but JS addEventListeners
Replace jQuery code with VanillaJS
console.clear()
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.addEventListener('mousedown', Highlight)
}
function Highlight(e) {
e.preventDefault()
const tr = this
const rows = document.querySelectorAll('#tbl > tbody > tr');
for (row of rows) {
row.classList.remove('highlight')
row.classList.add('highlight-siblings')
}
tr.classList.remove('highlight-siblings')
tr.classList.add('highlight')
}
/* 1. */
tr {
background-color: aquamarine;
}
tr.highlight-siblings{
background-color: green;
}
tr.highlight{
background-color: red;
}
<table id="tbl">
<tr>
<td>
v1
</td>
<td>
v1
</td>
<td>
v1
</td>
</tr>
<tr>
<td>
v2
</td>
<td>
v2
</td>
<td>
v2
</td>
</tr>
<tr>
<td>
v3
</td>
<td>
v3
</td>
<td>
v3
</td>
</tr>
</table>
I have many tables each one with an ID, (table1,2,3,...), and in each one I have many TD's <td><a href
example :
<table id="myTable1" class="someclass">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
<table id="myTable2" class="someclasse">
<tbody>
<tr>
<td>blablabla</td>
<td>random text</td>
<td>randomtext</td>
</tr>
</tbody>
</table>
</td>
(don't look at the HTML code it's not important for now )
My goal is to open all hrefs within the table "table X" then open them in new tab. I do that with
var els = document.getElementById("myTable1").querySelectorAll("a[href^='https://domaine.']");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
alert(el)
window.open (el,"_blank");
}
It works like a charm. Now I want to add a checkbox to each table, and if checked to open the href on "the" table I checked (I did some innerHTML to "insert" checkbox). Now my question, how can I get the table ID when I'll check the checkbox?
For example I check the table that have "table6" and then every link in that table gets opened.
table id=1 (checkbox)
table id=2 (checkbox)
etc
if i check the checkbox it will get the table with id 2
You can use closest to get the closest table, then you can get the id from that.
// List of checkboxes
let inputs = Array.from(document.querySelectorAll('input[type=checkbox]'))
// Add a click event to each
inputs.forEach(input => {
input.addEventListener('click', e => {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
})
})
<table id="abc">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="def">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="ghi">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
<table id="jkl">
<tr>
<td><input type="checkbox"></td>
</tr>
</table>
You say that you are adding the checkbox dynamically, so you won't want to do a querySelectorAll like I did above. You will want to add it when it is created like this:
// List of tables
let tables = Array.from(document.querySelectorAll('table'))
// insert the checkbox dynamically
tables.forEach(table => {
table.innerHTML = '<tr><td><input type="checkbox"></td></tr>'
// Get the checkbox
let checkbox = table.querySelector('input[type=checkbox]')
// Add an eventlistener to the checkbox
checkbox.addEventListener('click', click)
})
function click(e) {
let target = e.currentTarget
// If the checkbox isn't checked end the event
if (!target.checked) return
// Get the table and id
let table = target.closest('table')
let id = table.id
console.log(id)
}
<table id="abc">
</table>
<table id="def">
</table>
<table id="ghi">
</table>
<table id="jkl">
</table>
…I want to add a checkbox to each table, and if [it's] checked…open the href [in] "the" table I checked…how can I get the table ID when I'll check the checkbox?
Given that you want to find the id of the <table> within which the check-box <input> is contained in order to select the <table> via its id property you don't need the id; you simply need to find the correct <table>.
To that end I'd suggest placing an event-listener on each of those <table> elements, and opening the relevant links found within. For example (bearing in mind that there are restrictions on opening new windows/tabs on Stack Overflow, I'll simply style the relevant <a> elements rather than opening them):
function highlight(e) {
// here we find the Static NodeList of <a> elements
// contained within the <table> element (the 'this'
// passed from EventTarget.addEventListener()) and
// convert that Array-like collection to an Array
// with Array.from():
Array.from(this.querySelectorAll('a'))
// iterating over the Array of <a> elements using
// Array.prototype.forEach() along with an Arrow
// function:
.forEach(
// here we toggle the 'ifCheckboxChecked' class-name
// via the Element.classList API, adding the class-name
// if the Event.target (the changed check-box, derived
// from the event Object passed to the function from the
// EventTarget.addEventListener function) is checked:
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
// converting the Array-like Static NodeList returned
// from document.querySelectorAll() into an Array:
Array.from(document.querySelectorAll('table'))
// iterating over the Array of <table> elements:
.forEach(
// using an Arrow function to pass a reference to the
// current <table> element (from the Array of <table>
// elements to the anonymous function, in which we
// add an event-listener for the 'change' event and
// bind the named highlight() function as the event-
// handler for that event:
table => table.addEventListener('change', highlight)
);
function highlight(e) {
Array.from(this.querySelectorAll('a'))
.forEach(
link => link.classList.toggle('ifCheckboxChecked', e.target.checked)
);
}
Array.from(document.querySelectorAll('table')).forEach(
table => table.addEventListener('change', highlight)
);
body {
counter-reset: tableCount;
}
table {
width: 80%;
margin: 0 auto 1em auto;
border: 1px solid limegreen;
}
table::before {
counter-increment: tableCount;
content: 'table' counter(tableCount);
}
a.ifCheckboxChecked {
background-color: #f90;
}
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td><input type="checkbox"></td>
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
</tbody>
</table>
JS Fiddle demo.
References:
CSS:
::before pseudo-element
Using CSS Counters.
JavaScript:
Array.from().
Array.prototype.forEach().
Arrow Functions.
Element.querySelectorAll().
Event.
EventTarget.addEventListener().
I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click "add" button, a new row gets added to the table, but when I click the "delete" button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
function deleteRow(row){
var d = row.parentNode.parentNode.rowIndex;
document.getElementById('dsTable').deleteRow(d);
}
HTML code
<table id = 'dsTable' >
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
</table>
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>
jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.
Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
Here is working code: http://jsfiddle.net/hX4f4/2/
I would try formatting your table correctly first off like so:
I cannot help but thinking that formatting the table could at the very least not do any harm.
<table>
<thead>
<th>Header1</th>
......
</thead>
<tbody>
<tr><td>Content1</td>....</tr>
......
</tbody>
</table>
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example:
http://jsfiddle.net/p9dey/1/
Use the following code to delete the particular row of table
<td>
<asp:ImageButton ID="imgDeleteAction" runat="server" ImageUrl="~/Images/trash.png" OnClientClick="DeleteRow(this);return false;"/>
</td>
function DeleteRow(element) {
document.getElementById("tableID").deleteRow(element.parentNode.parentNode.rowIndex);
}
try this for insert
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
and this for delete
document.getElementById("myTable").deleteRow(0);
Yeah It is working great
but i have to delete from localstorage too, when user click button , here is my code
function RemoveRow(id) {
// event.target will be the input element.
// console.log(id)
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);// the row to be removed
// const books = JSON.parse(localStorage.getItem("books"));
// const newBooks= books.filter(book=> book.id !== books.id);
// console.log(books, newBooks)
// localStorage.setItem("books", JSON.stringify(newBooks));
}
// function RemoveRow(btn) {
// var row = btn.parentNode.parentNode;
// row.parentNode.removeChild(row);
// }
button tag
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}
Hi I would do something like this:
var id = 4; // inital number of rows plus one
function addRow(){
// add a new tr with id
// increment id;
}
function deleteRow(id){
$("#" + id).remove();
}
and i would have a table like this:
<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)
I have a page with several rows containing information, made by several users. I'm looking for a way to highlight the all the users rows on mouseover.
This "Highlight multiple items on hover's condition" almost solved my problem, but since the classes or id's in my problem are dynamic from a database, and would contain an identifier from the DB and are unique each time. I have not been able to apply it.
Example code: https://jsfiddle.net/3cehoh78/
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2a</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4a</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
</table>
<br>
<br>
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1b</td>
<td class="cellclass">Sauron</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4b</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 5b</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
</table>
In this example, I want all the rows with "Sam" to be highlighted on mouseover on one of them, so rows 1a,3a,2b,3b.
I was thinking of adding a class to all the Sam rows when generating the tables (Sam has a unique user ID), but how do I then change css that affects all the rows on mouseover (and not just one).
Please note that I cant pre-add css classes for all the unique userID's, this is just an example.
Here a solution with JQuery https://jsfiddle.net/3cehoh78/5
$(document).ready(function() {
$( "tr" ).hover(function() {
var search = $(this).find("td:eq(1)").text();
$( ".highlight" ).removeClass("highlight");
$("tr:contains('"+search+"')").addClass("highlight");
}); /* END HOVER */
}); // end document ready
Simple solution without using jQuery and co: https://jsfiddle.net/3cehoh78/3/
var rows = [].slice.call(document.querySelectorAll('.testtable tr'));
rows.forEach(function(row) {
row.addEventListener('mouseover', function() {
resetHighlighting();
var name = row.querySelector('td:nth-child(2)').textContent;
rows.forEach(function(r) {
if (r.querySelector('td:nth-child(2)').textContent === name) {
r.classList.add('highlighted');
}
});
});
});
function resetHighlighting() {
rows.forEach(function(row) {
row.classList.remove('highlighted');
});
}
Here's another way using vanilla-JavaScript.
var tds = document.querySelectorAll('td');
var highlight = function () {
// take this person's name from the 2nd cell
var name = this.parentNode.children[1].innerHTML;
// highlight cells with same name
tds.forEach(function (td) {
var tr = td.parentNode;
// compare other's person name with this person name
// highlight if there is a match
tr.classList.toggle('highlight', tr.children[1].innerHTML === name)
});
}
// attach an event listener to all cells
tds.forEach(function (td) {
td.onmouseover = highlight;
});
Demo
I want give every element in a table a generated id. See this html table below:
<table>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>
A3
</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>
B3
</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
</tr>
</tbody>
</table>
I want to give each element an id using breadth-first traversal. So, the result becomes like this:
<table>
<tbody id="0">
<tr id="1">
<td id="4">A1</td>
<td id="5">A2</td>
<td id="6">
A3
</td>
</tr>
<tr id="2">
<td id="7">B1</td>
<td id="8">B2</td>
<td id="9">
B3
</td>
</tr>
<tr id="3">
<td id="10">C1</td>
<td id="11">C2</td>
<td id="12">C3</td>
</tr>
</tbody>
</table>
I have tried the each() function in jQuery to generate the id for every element in that table, but the traversal algorithm used in each() function is pre order traversal.
Can anyone suggest me the Javascript code to do this?
var n = 0
var level = $("table");
while (level.children().length) {
level = level.children().each(function(_, el) {
el.id = n++;
})
}
DEMO: http://jsfiddle.net/J5QMK/
If you want to avoid the redundant .children() call, you can do this:
while ((level = level.children()).length) {
level.each(function (_, el) {
el.id = n++;
})
}
DEMO: http://jsfiddle.net/J5QMK/1/
A common way to do a breadth-first search is to use a queue as follows:
jQuery(document).ready(function () {
var ctr = 0;
var queue = [];
queue.push(jQuery("table").children()); // enqueue
while (queue.length > 0) {
var children = queue.shift(); // dequeue
children.each(function (ix, elem) {
queue.push( // enqueue
jQuery(elem).attr("id", ctr++).children();
);
console.log(elem.tagName + ": " + elem.id);
});
}
});