Remove table row by finding content with Javascript - javascript

i have this code:
<table>
<tbody>
<tr>
<td align="left">X</td>
<td>X1</td>
</tr>
<tr>
<td width="150" align="left">Y</td>
<td>Y1</td>
</tr>
<tr>
<td align="left">Status: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
<tr>
<td width="150" align="left">Z</td>
<td>Z1</td>
</tr>
</tbody>
</table>
and want to remove with Javascript this line:
<tr>
<td align="left">Status: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
the problem is that i don't have any id's or classes for identification.
is there a way to remove the row by searching "Status: " or name="status" with javascript for Firefox only (using it for Greasemonkey)?
i can't use jQuery and i can't edit the code to set any id's
best regards
bernte

If you can afford not being compatible with IE7, You can do that :
​var elements = document.querySelectorAll('td[align="left"]');
for (var i=0; i<elements.length; i++) {
var text = elements[i].textContent || elements[i].innerText;
if (text.trim()=='Status:') {
elements[i].parentNode.parentNode.removeChild(elements[i].parentNode);
}
}
Demonstration
To be compatible with IE7, you'd probably have to iterate on all rows and cells, which wouldn't really be slower but would be less clear.
Note that I used trim which doesn't exist on IE8. To make it work on this browser if needed, you might add this usual fix (from MDN) :
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}

function removeRowByCellValue(table,cellValue) {
var cells = table.getElementsByTagName("TD");
for(var x = 0; x < cells.length; x++) {
// check if cell has a childNode, prevent errors
if(!cells[x].firstChild) {
continue;
}
if(cells[x].firstChild.nodeValue == cellValue) {
var row = cells[x].parentNode;
row.parentNode.removeChild(row);
break;
}
}
}
First get a reference to your table, since you do not have an ID you can use getElementsByTagName.. (here i'm assuming that it is the first table in your document)
var myTable = document.getElementsByTagName("table")[0];
Then you can invoke the function with the following parameters
removeRowByCellValue(myTable,"Status: ");

var xpathResult = document.evaluate("//td[starts-with(.,'Status:')]", document.body, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var element = xpathResult.singleNodeValue.parentNode;
while (element.firstChild)
element.removeChild(element.firstChild);
Jsbin http://jsbin.com/urehuw/1/edit

And if you'd like to be compatible with older IE:
function closest(el, tag) {
if (!el || !tag) {
return false;
}
else {
return el.parentNode.tagName.toLowerCase() == tag ? el.parentNode : closest(el.parentNode, tag);
}
}
// gets all 'select' elements
var sel = document.getElementsByTagName('select');
// iterates through the found 'select' elements
for (var i=0, len = sel.length; i<len; i++) {
// if the 'select' has the name of 'status'
if (sel[i].name == 'status') {
// uses the closest() function to find the ancestor 'tr' element
var row = closest(sel[i], 'tr');
// access the 'tr' element's parent to remove the 'tr' child
row.parentNode.removeChild(row);
}
}
JS Fiddle demo.

simply use this
var gettag =document.getElementsByTagName("tr")[3] ; // the third tag of tr
document.removeChild(gettag);

Related

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

How can I fix jquery when i change table elements to div style in body section?

<body>
<input type="text" id="search"/>
<table id="boxdata">
<tr>
<td class="namebox1">jQuery</td>
</tr>
<tr>
<td class="namebox2">javascript</td>
</tr>
<tr>
<td class="namebox3">php</td>
</tr>
<tr>
<td class="namebox4">sql</td>
</tr>
<tr>
<td class="namebox5">XML</td>
</tr>
<tr>
<td class="namebox6">ASP</td>
</tr>
</table>
</body>
<script>
$(document).ready(function(){
$('#search').keyup(function(){
searchBox($(this).val());
});
});
function searchBox(inputVal) {
$('#boxdata').find('tr').each(function(index, row){
var names = $(row).find('td');
var found = false;
if(names.length > 0) {
names.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()) & inputVal != ''){
found = true;
return false;
}
});
if(found == true)
$(row).addClass("red");
else
$(row).removeClass("red");
}
});
}
</script>
there's a textfield for searching words and there are 6 words in the each 6 boxes below textfield.(I omitted css codes. but, it wouldnt matter to solve the problem.). if i type a letter 's' then the words that including letter 's' like 'javascript', 'sql', 'ASP' these font-color will be changed black to red. And i made it by using table elements in html but i'd like to change all elements into div style to put some data fluidly later. i have difficulty to fix especially jquery. how can i fix it?
You can simplify this a little bit.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal, 'i');
$('#boxdata').find('tr').removeClass('red').filter(function() {
return $(this).find('td').filter(function() {
return regExp.test( $(this).text() );
}).length && $.trim(inputVal).length;
}).addClass('red');
}
So remove the red class from all <tr>'s first, then filter them, test the text of each <td>, if it matches, return the <tr> and then add the class red again.
Here's a fiddle
As for changing from a table to div, the jQuery would depend on how you structure your markup, but the principle would remain the same.
Here's another fiddle
You can make javascript code HTML agnostic by using css classes instead of element names. Demo.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal = $.trim(inputVal), 'i'),
highlight = 'red';
$('#wrapper').find('.word') //instead of tr/td/div
.removeClass(highlight)
.each(function(){
var $this = $(this);
inputVal && regExp.test($this.text()) &&
$this.addClass(highlight);
});
}

How to put an onclick event for a HTML table row created dynamically through java script.?

I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.

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');

Why would a script differ in evaluating 'element.checked' in the same script, acting on different table-rows with the same structure?

I wrote an answer to this question: Fetch content of next td on checkbox click, the answer was accepted (as of writing this question).
The intent was to find the text-value of the table-cell following the current cell that contained the input checkbox; for the second row this works (in Chrome 18/WinXP), but in the first row the evaluation console.log(that.checked); evaluates to false (regardless, so far as I can see, of it being checked or not).
The supplied HTML:
<table>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOOBAR
</td>
<td width=73%>
BAZ
</td>
</tr>
<tr>
<td>
<input type=checkbox name=t>
</td>
<td width=25%>
FOO
</td>
<td width=73%>
BAR
</td>
</tr>
</table>
And my JavaScript:
var c = [];
c = window.document.getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
var that = c[i];
if (that.type == 'checkbox') {
that.onchange = function() {
console.log(that.checked);
if (that.checked){
console.log(that.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
};
}
}​
JS Fiddle demo.
Note that it seems to work reliably for the second row (and logs FOO to the console), but in the first row the console logs only false. Is there an obvious mistake I'm making?
You're actually running into an issue unrelated to checked. Your that variable is outside the scope of the event handler, and so it is always resolving to c[1]. You need to either wrap the thing in a closure (aka function () { ... }(); or just change that to this inside your event handler, like in this: http://jsfiddle.net/z88HH/3/
for (var i = 0; i < c.length; i++) {
var that = c[i];
if (that.type == 'checkbox') {
that.onchange = function() {
console.log(this.checked);
if (this.checked){
console.log(this.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
};
}
}​
Isn't that always the last row e.g. try console.log(that, that.checked) , wrap it in a closure see your edited jsFiddle
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox') {
c[i].onchange = function(){
var that = c[i];
return function() {
console.log(that, that.checked);
if (that.checked){
console.log(that.parentNode.nextElementSibling.firstChild.nodeValue.trim());
}
}}();
}
}​

Categories

Resources