How do I remove an element from the DOM, given its id? - javascript

In this specific case, the element is a table row.

Untested but something like:
var tbl = document.getElementById('tableID');
var row = document.getElementById('rowID');
tbl.removeChild(row);
or
var row = document.getElementById('rowID');
row.parentNode.removeChild(row);

var row = document.getElementById("row-id");
row.parentNode.removeChild(row);

var zTag = document.getElementById ('TableRowID');
zTag.parentNode.removeChild (zTag);
Or in jQuery:
$('#TableRowID').remove ();

Jquery
$('#myTableRow').remove();
This works fine if your row has an id, such as:
<tr id="myTableRow"><td>blah</td></tr>
Pure Javascript :
Javascript Remove Row From Table
function removeRow(id) {
var tr = document.getElementById(id);
if (tr) {
if (tr.nodeName == 'TR') {
var tbl = tr; // Look up the hierarchy for TABLE
while (tbl != document && tbl.nodeName != 'TABLE') {
tbl = tbl.parentNode;
}
if (tbl && tbl.nodeName == 'TABLE') {
while (tr.hasChildNodes()) {
tr.removeChild( tr.lastChild );
}
tr.parentNode.removeChild( tr );
}
} else {
alert( 'Specified document element is not a TR. id=' + id );
}
} else {
alert( 'Specified document element is not found. id=' + id );
}
}

Related

Filtering results in a table

I have a PHP page and a table where I fill it up with data from the database. I have a search field on top of the table where I would like to filter rows as I am typing.
Here is my Javascript
$('#system-search').keyup( function()
{
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table table-filter tbody');
var tableRowsClass = $('.table table-filter tbody tr');
$('.search-sf').remove();
tableRowsClass.each( function(i, val)
{
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if(inputText != '')
{
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
}
else
{
$('.search-query-sf').remove();
}
if( rowText.indexOf( inputText ) == -1 )
{
//hide rows
tableRowsClass.eq(i).hide();
}
else
{
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if(tableRowsClass.children(':visible').length == 0)
{
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
Sorry for the bad code and formatting I can't seem to understand how to format it properly..
https://stackoverflow.com/a/19696936/1406155
You are using a bit too much code for that. First place an input field like this
<input type="text" id="search" placeholder="Search">
and use the below function for search
$("#search").keyup(function () {
var value = this.value.toLowerCase().trim();
$("table tr").each(function (index) {
if (!index) return;
$(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
});

Sorting dynamic table in jquery

Sorry but I'm completly new to js and jquery.
I got dynamic table which values are in localstorage. I can add new row, delete row, and edit cells. This is working.
I want to add a sorting this table by clicked colum. I found here code and try it. It just working when I write table and not use my javascript to add rows from localstorage. Table in two cases looks same in html code. I have no idead why sorting isnt working with dynamic table.
This is w/o my dynamic table from localstore, sorting as supposed to:
http://jsfiddle.net/eW8Kg/1/
This is with table from localstorage(not working in jsfiddle?) on my comupter this is working good, but table is not sorting! (I left this static values):
http://jsfiddle.net/XAu5G/
I think my problem can be in creation of table content:
var Html = "<tbody>";
for (var i = 1; i < localStorage.length; i++) {
var input = "<td><input style='border:hidden' class=\"fields\" name = " + localStorage.key(i) + " type='text' onchange='change(\"" + localStorage.key(i) + "\")' /></td>"
Html += "<tr class=\"field\">";
for (var j = 0; j < 4; ++j) {
Html += input;
}
var button = "<td><input type='button' value = 'UsuĊ„' onclick='Remove(\"" + localStorage.key(i) + "\")'></td>";
Html += button + "</tr>";
}
Html += "<tr id=\"actions\"></tr></tbody>"
document.getElementById("list").innerHTML += Html;
This jquery code do sorting:
$(document).ready(function() {
var table = $('#list');
jQuery.fn.sortElements = (function() {
var sort = [].sort;
return function(comparator, getSortable) {
getSortable = getSortable || function() {return this;};
var placements = this.map(function() {
var sortElement = getSortable.call(this),
parentNode = sortElement.parentNode,
// Since the element itself will change position, we have
// to have some way of storing it's original position in
// the DOM. The easiest way is to have a 'flag' node:
nextSibling = parentNode.insertBefore(
document.createTextNode(''),
sortElement.nextSibling
);
return function() {
if (parentNode === this) {
throw new Error(
"You can't sort elements if any one is a descendant of another."
);
}
// Insert before flag:
parentNode.insertBefore(this, nextSibling);
// Remove flag:
parentNode.removeChild(nextSibling);
};
});
return sort.call(this, comparator).each(function(i) {
placements[i].call(getSortable.call(this));
});
};
})();
$('#x').click(function(){
$('#list').hide();
});
$('#nazwa-header').wrapInner('<span title="sort this column"/>').each(function() {
var th = $(this),
thIndex = th.index(),
inverse = false;
th.on('click', function() {
table.find('td').filter(function() {
return $(this).index() === thIndex;
}).sortElements(function(a, b) {
console.log($(a).find('input').val(),$(b).find('input').val());
return $(a).find('input').val() > $(b).find('input').val() ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}, function() {
// parentNode is the element we want to move
return this.parentNode;
});
inverse = !inverse;
});
});
});

Get contents of the first cell in the clicked column and the first cell of the clicked row in a HTML table

I'm using the following javascript to get the data in a clicked table cell:
var table = document.getElementById('ThisWeek'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++)
{
cells[i].onclick = function()
{
document.getElementById("txtVal").value = this.innerText;
}
}
How can I modify this so I can also obtain the contents of the first cell in the clicked column and the first cell in the clicked row? E.g. if I click on "s" in the table below, I get the results "2" and "B" returned as two variables:
0 1 2 3
A q w e
B a s d
C z x c
Please note that I need a javascript solution, not jQuery. Ideally, I would also like clicks on the first row and first column to return empty strings.
This snippet uses the properties I've mentioned in my comment:
window.onload = function () {
var table = document.getElementById('table');
table.addEventListener('click', function (e) {
var target = e.target,
col = target.cellIndex,
row;
while (target = target.parentElement) {
if (!col && col !== 0) {
col = target.cellIndex;
}
if (target.tagName.toLowerCase() === 'tr') {
row = target.rowIndex;
break;
}
}
console.log(table.rows[row].cells[0].innerHTML + ', ' + table.rows[0].cells[col].innerHTML);
});
}
A live demo at jsFiddle.
I'd suggest:
function index(c){
var i = 0;
while (c.previousSibling){
/* if the previousSibling has a nodeType and that nodeType === 1
(indicating the previousSibling is an element) increment the i variable */
if (c.previousSibling.nodeType && c.previousSibling.nodeType === 1){
i++;
}
// reset c to the previousSibling
c = c.previousSibling;
}
/* i is the count of previous-siblings, and therefore the index
amongst those siblings: */
return i;
}
function getHeaders(e){
/* this is the table element,
e.target is the clicked element */
var el = e.target,
text = 'textContent' in document ? 'textContent' : 'innerText',
headers = [el.parentNode.getElementsByTagName('td')[0][text],this.getElementsByTagName('tr')[0].getElementsByTagName('td')[index(el)][text]];
// set the text of the nextElementSibling of the table:
this.nextElementSibling[text] = headers.join(', ');
}
document.getElementById('table').addEventListener('click', getHeaders);
JS Fiddle demo.
You can add this to your cells[i].onclick function:
var row = this.parentElement; // TR
var table = row.parentElement.parentElement; // TBODY > TABLE
document.getElementById("columnVal").value = row.rowIndex && this.cellIndex ? table.rows[0].cells[this.cellIndex].innerText : "";
document.getElementById("rowVal").value = row.rowIndex && this.cellIndex ? row.cells[0].innerText : "";

parentNode.rowIndex not working in chrome

I am adding listeners to the cells of the table so that i can get the cell index when a particular cell is clicked. However i am unable to get the value of row index in chrome. This works fine in IE10 and Firefox. The code is:
function AttachEvents() {
var cls = document.getElementById("TableContents").getElementsByTagName("td");
for ( var i = 0; i < cls.length; i++ ) {
if ( cls[i].addEventListener ) {
cls[i].addEventListener("click", alertRowCell, false);
} else if ( cls[i].attachEvent ) {
cls[i].attachEvent("onclick", alertRowCell);
}
}
}
function alertRowCell(e) {
var cell = e.target || window.event.srcElement;
//alert( cell.cellIndex + ' : ' + cell.parentNode.rowIndex );
if (cell.cellIndex == 1) {
alert(" The row index is " + cell.parentNode.rowIndex);
highlight();
}
}
How this can be resolved in Chrome?
You can easily refer to the clicked element with this.
In your case:
function alertRowCell(evt) {
var tr = this.parentNode;
// do something with tr...
}
The reason I'm saying it is because if your table structure is...
<tr>
<td><span>Hello</span></td>
</tr>
... then e.target is span whose parentNode is td and not tr.
Try this example: http://jsfiddle.net/naJBq/

How to highlighted the selected row from repeater?

I have a repeater, and i just want that when i select or click on any row of it then that would be highlighted. I had tried some code of javascript which makes the selected row highlighted, but not unhighlighting when select any other row.My code is:-
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
any javascript's and style's code is:-
<style type="text/css">
.highlight
{
background-color: Red;
}
.selected
{
background-color: #ffdc87;
}
</style>
<script type="text/javascript">
function Select(obj) {
obj.className = 'selected';
var tbl = document.getElementById("Repaddressorbbl")
var firstRow = tbl.getElementsByTagName("TR")[0];
var tableRowId = tbl.rows[firstRow.getElementById("gh").parentNode.id];
alert(tableRowId);
var oldRow = tbl.rows[firstRow.getElementsByTagName("tr")[0].value];
if (oldRow != null) {
oldRow.className = '';
}
firstRow.getElementsByTagName("tr")[0].value = obj.rowIndex;
}
</script>
We can do it simply with code behind but the matter is it should be done only with jquery or javascript.
You can use code similar to this:
var INDEX = $(this).parent().children().index($(this));
$('#Repaddressorbbl tr:nth-child(' + INDEX + ')').addClass("highlight")
.siblings()
.removeClass("highlight"); // remove css class from other rows
It gets the rownumber of the TR and adds a CSS class while removing the same class from all other TRs.
i've added a function to select elements with a specific classname so you can easly search the dom for elements with that class
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
function Select(obj) {
var oldRow = document.getElementsByClassName('selected');
if(oldRow.length > 0)
oldRow[0].className = '';
obj.className = 'selected';
}
Update for jQuery:
$(document).ready(function() {
$("tr").click(function() {
$(this).addClass("highlight").siblings().removeClass("highlight");
}
}
Original answer:
If I understand you correctly, all of your table rows are defined like this:
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
And you want to set a class on the most recently clicked row so it looks selected, while clearing said class from the previously clicked/selected row?
If so, a much simplified version of your function should do it:
var selectedRow = null;
function Select(obj) {
if (obj != selectedRow) {
if (selectedRow != null) {
selectedRow.className = '';
}
obj.className = 'selected';
selectedRow = obj;
}
}
I don't understand what you're trying to do with the firstRow.getElementsByTagName("tr") stuff. Have you got nested tables?

Categories

Resources