Select all innerHTML of td in ul li hierarchy - javascript

I have an html structure as follows-
<ul id='abc'>
<li>
<table>
<tbody>
<tr>
<td>
A
</td>
</tr>
</tbody>
</table>
</li>
<li>
<table>
<tbody>
<tr>
<td>
B
</td>
</tr>
</tbody>
</table>
</li>
...
...
</ul>
I want to store A,B,C... values in an array using jquery.Please help...

You can use $.fn.map()
Translate all items in an array or object to new array of items.
var arr = $('#abc td').map(function(){
return $(this).text();
}).get();

you can do this by javascript by The
Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name
var values = []
var tableUl = document.getElementById("abc");
var cells = tableUl.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
values.push( cells[i].textContent.trim());
}
fiddle

Here is what you want:
var values = [];
$('ul li').find('td').each(function() {
values.push($(this).html());
});

Try utilizing .text() , String.prototype.match()
var res = $("#abc td").text().match(/\w+/gi)
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul id='abc'>
<li>
<table>
<tbody>
<tr>
<td>
A
</td>
</tr>
</tbody>
</table>
</li>
<li>
<table>
<tbody>
<tr>
<td>
B
</td>
</tr>
</tbody>
</table>
</li>
</ul>

This should work:
var values = $('ul#abc td').map(function() { return $(this).text(); });

Another way would be:
$("ul#abc li td:first-child").each(function () {
//alert($(this).text());
console.log($(this).text());
});

Related

How do I get and pass the field of the row having class="name" in the following html?

<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata(parameter)">Fetch Details</button>
</td>
</tr>
</tbody>
In the above html, I want that the function fetchdata('parameter') to contain the text content of the td which has a class of name and is hidden, as the parameter.
OR
I need a way in which I can get the text content of the td having class of name in my javascript function.
i.e.
function fetchdata() {
const name = document.somethingThatGivesMeName()
}
NOTE: There are going to be multiple rows that I may require to get the name of so I can't directly do document.queryselector('.name')
Sorry, This might be pretty simple but I can't quite figure it out.
When clicking the button find the first row up in the tree relative to the button with the closest method. Then from the row select the element with the class name and read the textContent or innerText of that element.
const buttons = document.querySelectorAll('.js-fetch-details');
function fetchDetails(event) {
const row = event.target.closest('tr');
const name = row.querySelector('.name').textContent;
console.log(name);
}
buttons.forEach(button => button.addEventListener('click', fetchDetails));
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button class="js-fetch-details">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
You just need the quotes ':
function fetchdata(value){
console.log(value)
}
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata('parameter')">Fetch Details</button>
</td>
</tr>
</tbody>
or you can use event listener and data value:
document.querySelectorAll('button').forEach(el => {
el.addEventListener('click', e => {
e = e || window.event;
e = e.target || e.srcElement;
console.log(e.dataset.value)
})
})
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button data-value="parameter">Fetch Details</button>
</td>
</tr>
</tbody>
You can use document.getElementsByClassName('name')
This will get all the elements that have class of name.
I would put the listener on the <tbody> instead.
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.parentNode.parentNode.querySelector('.name').textContent;
console.log(name);
}
});
UPDATE
closest would also work
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.closest('tr').querySelector('.name').textContent;
console.log(name);
}
});
First you get all elements with class="name", then you pick just (the first) one with the attribute "hidden".
It's a way to do it anyway.
function fetchdata() {
const tds = document.getElementsByClassName("name")
for(let i = 0; i < tds.length; i++){
if(tds[i].getAttribute("hidden") != null) {
console.log(tds[i].innerHTML)
}
}
}
<table>
<tr>
<td class="name">gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td class="name">1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
With jQuery you can just do:
function fetchdata() {
console.log($('.name[hidden]').html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
Note that you need to have a table around your structure for any of this to work properly. You can't have tbody, tr and td outside a table.
If you use document.getElementsByClassName you will get what you want.
However, if there will be a case where more than one instance of that class name will occur, then you need to iterate through the classes and get their values.
The following should solve your problem
<html>
<head>
<script>
function fetchdata(){
var data = document.getElementsByClassName("data");
var t = data.length;
for(i = 0; i< t; i++){
var content = data[i].innerHTML;
alert (content);
}
}
</script>
<body>
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="data" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Get all global attribute values within an Id, tbody, tr, title

Using pure javascript
My code
<div id="all-items">
<table>
<tbody>
<tr title="Text 1"></tr>
<tr title="Text 2"></tr>
<tr title="Text 3"></tr>
</tbody>
</table>
</div>
I know with jQuery I can use
$("#all-items table tbody tr").title
will return
"Text 1"
but jQuery isn't working with my front end framework I'm using for some reason. In addition, I want to return all the values of the title attributes on the page within table rows.
using javascript only...
var rows = document.getElementById('all-items').getElementsByTagName('tr')
var titles = [];
for (var i = 0; i < rows.length; i++) {
titles.push(rows[i].getAttribute("title"));
}
console.log(titles);
<div id="all-items">
<table>
<tbody>
<tr title="Text 1"></tr>
<tr title="Text 2"></tr>
<tr title="Text 3"></tr>
</tbody>
</table>
</div>
The #WalksAway answer is fine. If you would like to reuse your jQuery selector though, you might look at querySelectorAll() as well.
var items = Array.from(document.querySelectorAll("#all-items table tbody tr"));
var titles = items.map(function(item) { return item.title; });
console.log(titles);
<div id="all-items">
<table>
<tbody>
<tr title="Text 1"></tr>
<tr title="Text 2"></tr>
<tr title="Text 3"></tr>
</tbody>
</table>
</div>

2D loops for building a table

I want to loop through a two-dimensional structure in angularjs to display it in a table. The data looks as follows:
data = {
"keyA": ["valueA", "valueB"],
"keyB": ["valueC", "valueD"]
}
the output should look like this:
<table>
<tr>
<th>keyA</th>
<td>valueA</td>
</tr>
<tr>
<th>keyA</th>
<td>valueB</td>
</tr>
<tr>
<th>keyB</th>
<td>valueC</td>
</tr>
<tr>
<th>keyB</th>
<td>valueD</td>
</tr>
</table>
at the moment my angular enriched html doesn't work and looks as follows:
<table>
<div ng:repeat="(key, values) in data">
<div ng:repeat="value in values">
<tr>
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
</div>
</div>
</table>
In this case I'm using the <div> element, but it doesn't work because obviously a <div> doesn't belong into a <table> like that. Is there some find of a No-Op-Element, which I have to use for loops like this?
I'm not sure if that's possible. Maybe someone can be a little more creative then I. You could try something like this though:
Controller-
var data = {
"keyA": ["valueA", "valueB"],
"keyB": ["valueC", "valueD"]
};
$scope.getPairs = function() {
var ret = [];
for(var key in data) {
for(var i = 0; i < data[key].length; i++) {
ret.push(key, data[key][i]);
}
}
return ret;
}
HTML -
<table>
<tr ng-repeat="pair in getPairs() track by $index">
<td>{{pair[0]}}</td>
<td>{{pair[1]}}</td>
</tr>
</table>
You could add ngRepeat on <tr> and <tbody> element:
<table>
<tbody ng-repeat="(key, values) in data">
<tr ng-repeat="value in values">
<th>{{key}}</th>
<td>{{value}}</td>
</tr>
</tbody>
</table>
Plunker

Unable to remove rows from table

I am having the table with following data in it
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>
I would like to delete the row based on the particular data given in table.
But I don't have any idea on how to delete the rows based on the particular data
Try this:
var table = document.querySelector('table');
var filterInput = document.querySelector('#filter');
filterInput.onkeyup = function () {
var val = this.value;
var td = table.getElementsByTagName('td');
var rows = [];
[].slice.call(td).forEach(function (el, i) {
if (el.textContent === val) {
rows.push(el);
}
});
rows.forEach(function(el) {
el.parentNode.style.display = 'none';
});
};
<input type="text" id="filter" placeholder="Hide row containing...">
<table>
<tr>
<td>cat</td>
<td>dog</td>
</tr>
<tr>
<td>hen</td>
<td>cock</td>
</tr>
</table>
Find the required element and then use style property to hide it. In the example, I went onto hide the table data element corresponding to the data dog.
var tds = $("td");
for(var i =0 ; i< tds.length ; i++)
{
var tdval = tds[i].innerHTML;
if(tdval.trim()=="dog")
{
document.getElementsByTagName("td")[i].style.display = "none";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>

How to get value from TD column using this.value

<table>
<tr onClick = "alert(this.FirstTDValue);" >
<td>123</td>
<td>Hello</td>
<td>Goodbye</td>
</tr>
</table>
How would this.FirstTDValue be accomplished so that alert would show '123', would it be efficient to request it at the TR or the Table level?
Table rows have a cells collection that is a live NodeList of the cells, so:
alert(this.cells[0].textContent || this.cells[0].innerText);
Or perhaps:
alert(this.cells[0].firstChild.data);
<tr> elements have a cells collection that lets you access the child <td> elements:
this.cells[0].innerHTML
Something like...
<tr onClick = "getTD();" >
<td>123</td>
<td>Hello</td>
<td>Goodbye</td>
</tr>
<script type="text/javascript">
function getTD(){
alert(document.body.getElementsByTagName("td")[0]);
}
</script>
This is how I did it:
<script>
Element.prototype.FirstTDValue = function() {
for (var i = 0; i< this.childNodes.length; i++) {
if (this.childNodes[i].tagName == 'TD') {
return this.childNodes[i].innerHTML;
}
}
return ("No TD Values");
}
</script>
<table>
<tr onClick = "alert(this.FirstTDValue())" >
<td>123</td>
<td>Hello</td>
<td>Goodbye</td>
</tr>
</table>
jQuery Solution:
<tr onClick="alert( $(this).children().first().text() )" >

Categories

Resources