I'm trying to get to this ID (contentContainer) in a webpage:
... //code before is OK, i can get values, etc. Then comes this:
<!-- *********************** CONTENT BELOW ************************** -->
<table align="center" id="contentContainer" width="100%">
It seems I can't get to this part of the code (after that line with CONTENT BELOW). I tryed to use the code in Tampermonkey:
var a= document.getElementById("contentContainer").length;
console.log(a);
I can use this kind of var check to the code before that code, without any problem. Any Ideas of whats happening and how to get the code I want (in contentContainer)?
A single DOM node doesn't have a .length property. A node list, which is an array-like collection of HTML elements does.
var tbl = document.getElementById("contentContainer"); // Get a reference to the single table node
console.log(tbl); // Log what was refererenced
// Get a reference to all of the row elements in the table
// (which returns a node list).
var rows = tbl.querySelectorAll("tr");
console.log(rows.length); // Log how many nodes are in the node list
<table align="center" id="contentContainer" width="100%">
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
</tr>
</table>
Without other information it seems that your call to get the element by Id is trying to get the length property at the same time which will fail to get the element in the first place. So try getting rid of the .length.
Related
I'm new to js, I'm working on a chrome extension and am having confusion webscraping a website. Suppose I have a simple table in an html like this
<html>
<body>
<table class="birthdays">
<tbody><tr>
<th>date</th>
<th>month</th>
<th>year</th>
</tr>
<tr class="r0">
<td>Person</td>
<td>1</td>
<td>Jan</td>
<td>77</td>
<td colspan="3"></td>
</tr>
<tr class="r0">
<td>Person</td>
<td>1</td>
<td>Jan</td>
<td>77</td>
<td colspan="3"></td>
</tr>
</tbody></table>
</body>
</html>
In my chrome extension when I do
const x = document.getElementsByTagName("th")[0][0]
alert(x)
It says it found a th object, but doesn't give me the actual data. That's the first issue, my actual goal is to determine if all elements in the tr tags have the same of one property (ex. if everyone has their birthday in Jan, open a tab).
document.getElementsByTagName
returns HTMLCollection https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
it's an array-like object (not real array)
and you can get the value from it calling item() method https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection/item
Seems that you need something like this document.getElementsByTagName("th").item(0).innerHTML to get content of the first TH tag
This is not a complete answer, but in javascript the container is not its contents - i.e. you need document.getElementsByTagName("th")[0][0].innerHTML to get at the 'date' string.
it's my first question here, but I'm learning from stackoverflow since years now.
In my local application (PHP, MySql, Html, Javascript) I have a jQuery datatable, and in the last column the user can show (as PDF) or delete a row by clicking on an icon (-> uses fontawesome).
The data in the table comes in with Ajax from a JSON file.
Here is the datatable HTML code:
<tbody>
<tr role="row" class="odd">
<td class="sorting_1" tabindex="0">customer 1</td>
<td class=" dt-body-center">
<i class="fa fa-search-plus"></i>
<span data-cid="25" data-ordid="223150"><i class="fa fa-trash-alt"></i></span>
</td>
</tr>
...
For deleting a row I formerly started a Javascript function, with an Ajax request doing the needed operations on the database, but I wasn't able to integrate the functionality of deleting the row from my datatable.
Then I changed my strategy starting from the datatable triggering the click event on the icon.
With this I am able to successfully delete the row from the datatable (NOT the database!) but I wasn't able to figure out how to grab the needed ID's for launching the delete operations.
I write these ID's (customer-id: cid, order-id: ordid) in < span data-id=cid, data-ordid=ordid>.
var table1 = $('#myTable1').DataTable();
$('#myTable1 tbody').on('click', 'i.fa-trash-alt', function () {
table1
.row($(this).parents('tr'))
.remove()
.draw();
});
My problem is that I am not able to get the ID's in the < span>. Looking at the (Firefox) debugger I can see them under "(this) - parentElement: span - dataset: DOMStringMap(2) - cid:25 and ordid:223150".
Tried things like: "var cid = table1.row($(this).dataset('cid')" and variants but nothing worked for me and unfortunately my jQuery knowledge is very basic.
Have searched an answer for hours now, but didn't find the solution.
Can someone point me in the right direction please or even give some explanation how to grab a value with jQuery seeing the exact position in the Firefox debugger?
You can try the following code, you can receive event object in listener and then get attributes from it's parent span.
$(document).ready(function(){
var table1 = $('#myTable1').DataTable();
$('#myTable1 tbody').on('click', 'i.fa-trash-alt', function (e) {
//you can get ids from parent span attribute like:
var cId = e.target.parentNode.attributes['data-cid'].value;
var ordId = e.target.parentNode.attributes['data-ordid'].value
alert(cId);
table1
.row($(this).parents('tr'))
.remove()
.draw();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="myTable1">
<thead>
<tr>
<th>title-1</th>
<th>title-2</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd">
<td class="sorting_1" tabindex="0">customer 1</td>
<td class=" dt-body-center">
another column
</td>
<td><span data-cid="25" data-ordid="223150"><i class="fa-trash-alt">Delete</i></span></td>
</tr>
</tbody>
</table>
I want to select a particular column of a table and sort it accordingly using Javascript (No frameworks or plugins). Could anyone help me regarding this?
<table>
<thead>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data11</td>
<td>Data23</td>
<td>Data53</td>
<td>Data45</td>
</tr>
<tr>
<td>Data81</td>
<td>Data42</td>
<td>Data33</td>
<td>Data4854</td>
</tr>
<tr>
<td>Data84681</td>
<td>Data452</td>
<td>Data354</td>
<td>Data448</td>
</tr>
<tr>
<td>Data1846</td>
<td>Data25635</td>
<td>Data3232</td>
<td>Data44378</td>
</tr>
</tbody>
</table>
function sortTableByColumn(tableId,columnNumber) { // (string,integer)
var tableElement=document.getElementById(tableId);
[].slice.call(tableElement.tBodies[0].rows).sort(function(a, b) {
return (
a.cells[columnNumber-1].textContent<b.cells[columnNumber-1].textContent?-1:
a.cells[columnNumber-1].textContent>b.cells[columnNumber-1].textContent?1:
0);
}).forEach(function(val, index) {
tableElement.tBodies[0].appendChild(val);
});
}
In your page, add id to the table tag:
<table id="myTable">
From javascript, use:
sortTableByColumn("myTable",3);
tBodies[0] is used because there can be many. In your example there is only one.
If we have var arr=[123,456,789], [].slice.call(arr) returns a copy of arr.
We're feeding it the html-rows-collection, found in tBodies[0] of tableElement.
Then, we sort that array with an inline function that compares two array elements, here: rows (<tr>).
Using cells[columnNumber] we access the <td>s, and textContent to access the text content. I've used columnNumber-1 so you can enter 3 for third column instead of 2, because the index of first element of an array (column 1) is 0...
The forEach goes through the elements of the array, which is by now in order, and appendChild row to the tBody. Because it already exist, it just moves it to the end: moving the lowest value to the end, then moving the second lowest to the (new) end, until it ends with the highest value, at the end.
I hope this is what you want. If so, enjoy!
Try using datatables you can get it from http://datatables.net its reallt easy to use. depends on jQuery
$("table").dataTable();
boom! and its done.
I am trying to dynamically insert links to return to the top of the document at the end of every section of a web page (sad to say, but it's table-based layout). I'm using the jQuery filter() selector, and while I get no error, it's not making any changes in the browser output. When I use alert() with the variable, it says Object object. I understand that the problem is in the line where I define the filter itself, but I was unable to find a similar example, and I don't know how to fix it.
Here's the code:
HTML
<table>
<tr class="head"><td colspan="2">section title 1 </td></tr>
<tr><td>text</td>
<td><img /></td>
</tr>
<tr><td>text</td>
<td>< img /></td>
</tr>
<tr class="head"><td colspan="2">section title 2 </td></tr>
<tr><td>text</td>
<td><img /></td>
</tr>
<tr><td>text</td>
<td>< img /></td>
</tr>
<!-- you get the point -->
JavaScript
$(document).ready(function(){
var lastRow = $('tr').filter(function(){
return $(this).next()==$(".head"); // Here's the problem, IMO
});
var a = '<tr class="toTop"><td class="top" style="text-align:right" colspan="2">go to top ↑</td></tr>';
lastRow.after(a);
});
The script attempts to select each row that precedes a row with class="head" and insert a row with a top link.
That's because you are comparing 2 different objects that is always false, you should use is method or length property:
var lastRow = $('tr').filter(function(){
return $(this).next(".head").length;
// return $(this).next().is(".head");
});
However, I'd suggest using .prev() method:
$('tr.head').prev(); // selects the previous sibling tr element
I am trying to append table rows to an existing table.
This is how my table is structured:
<div id="productListContainer">
<table id="productListTable">
<thead>
<tr>
<td>
#
</td>
<td>
Product Name
</td>
<td>
Price
</td>
<td>
Quantity
</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
With the following function I am trying to append a new table row:
function(data) {
if (data.productAdded !== "undefined") {
$("#productListTable tr").append().html(data.productAdded);
}
}
Which successfully appends one row. However, if I select a different item which triggers the same function, then the added table row will be overwritten with the new one.
I am using this function within an ajax call as the success message.
'data' is a JSON object which contains productAdded which itself is the table row as a string.
What you want to do is append a row to the body of the table I assume. For this you'll need to do this -
$("#productListTable tbody").append(html_string);
Your html_string will need to contain all the necessary <tr> and <td> elements to match up with your table's header.
References -
.append() documentation - http://api.jquery.com/append/
jsFiddle demo
Calling .append() with no parameters, doesn't append anything, and returns the original jQuery object. So, when you call .html() you're replacing the <tr>'s contents.
It should be:
$("#productListTable tr").append(data.productAdded);
EDIT: That would append to the <tr> inside the <thead>. I assume you want to append to the <tbody>.
$("#productListTable tbody").append(data.productAdded);
EDIT 2: When appending to a table, you need to make sure you have a <tr> and the right number of <td>s in your string.