I'm using a css class to define grouping in table rows:
<table>
<tr class="otherClasses group1">...</tr>
<tr class="otherClasses group1">...</tr>
<tr class="otherClasses group2">...</tr>
<tr class="otherClasses group2">...</tr>
...
<tr class="otherClasses groupN">...</tr>
</table>
Now I need to loop through all the rows in my table and get groupX for each one. Then I'll split the string and extract group ID.
What's the correct/best way to get groupX class among all tr classes only giving group prefix?
You should be able to use attribute contains selector in jQuery:
$('tr[class*="group"]')
Have a look at jquery selectors documentation for more info. You may need to tweak the value depending on your specifics (e.g. add a space before group).
The following will return an array with "group" classes:
var groupClasses = $(".otherClasses").map(function() {
return (this.className.match(/group\d+/) || []).pop();
}).get();
Or in each() iteration:
$(".otherClasses").each(function() {
var groupClass = (this.className.match(/group\d+/) || []).pop();
// ...
});
Related
I am trying to use a button inside a table division to set a variable as the same value as another division in the same row, but whenever I run my code (below), it returns the value of all the table divisions concatenated together. I am unsure why this was happening, so I replaced '.children()' with 'childnodes[0]' to try and get only the first name, but this just doesn't work and I don't why.
My html looks like this:
<table>
<tr>
<td>John</td>
<td>Doe</td>
<td><button>Get First Name</button></td>
</tr>
</table>
And my Javascript is this:
$(document).ready(function(){
$("button").click(function(){
var first = $(this).closest("tr").childNodes[0].text();
alert(first)
})
});
set a variable as the same value as another division in the same row
there are lots of possibilities for this, here are some (with the most useful first (opinion based))
$("button").click(function() {
var first = $(this).closest("tr").find("td:first").text();
var first = $(this).closest("tr").find("td").first().text();
var first = $(this).closest("tr").find("td").eq(0).text();
var first = $(this).closest("tr").children().first().text();
var first = $(this).closest("tr").children().eq(0).text();
var first = $(this).closest("td").siblings().first().text();
});
it returns the value of all the table cells concatenated together
https://api.jquery.com/text
Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
because you're passing the "tr" to text() it gets the text of all the cells (tds) and their content etc and combines them as one, so you need to limit to the first as you've attempted.
however .childNodes[0] can only be applied to a DOM element/node, while $(this).closest("tr") gives you a jquery object/collection, which doesn't have .childNodes property.
So the jquery equivalent would be to use .children().eq(0).
You could use class identifiers to get information you need as well.
<table>
<tr>
<td><span class="first-name">John</span></td>
<td><span class="last-name">Doe</span></td>
<td>
<button class="btn-get-data" data-class="first-name">Get First Name</button>
<button class="btn-get-data" data-class="last-name">Get Last Name</button>
</td>
</tr>
</table>
$(document).ready(function() {
$(".btn-get-data").click(function() {
$btn = $(this);
$tr = $btn.closest('tr');
var first = $tr.find('.' + $btn.attr('data-class')).html();
alert(first);
})
});
If you make the button click generic like so, you can add additional buttons on the page and use that to get the class within that row.
Here is a working fiddle example: https://jsfiddle.net/b1r0nucq/
you could find the :first child and get his html(), as below:
$(document).ready(function() {
$("button").click(function() {
var first = $(this).closest("tr").children(":first").html();
alert(first)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>John</td>
<td>Doe</td>
<td><button>Get First Name</button></td>
</tr>
</table>
I have a table in HTML:
<tr class="inner2-top">
<td class="name1"> Hello </td>
</tr>
How would I get the name1 in a javascript variable function like this?
function grabData() {
var name = // todo
}
You want the data that's inside of the td?
function grabData(className) {
return document.getElementsByClassName(className)[0].innerText;
}
console.log(grabData("name1"));
I suggest using id attributes instead of class attributes if you're going to use this method, though. ids are unique whereas classes are not, which will explain why you get unexpected results if you have more than one element with the class "name1" etc.
var name = $(".name1").text();
Try the above
you can get that text using class selector
var getName=$('.name1').html();
alert(getName);
DEMO
What i'm trying to do is to get the cell of this where the classname is "revision_id".
<tr>
<td class="supplierOrderId">10790</td>
<td class="revision_id">#7</td>
<td class="supplier">DGI Developpement </td>
<td class="quantity">80</td>
<td class="stock">0</td>
<td class="purchase_price">10.00</td>
<td class="comments"> </td>
</tr>
I managed to do it this way :
revision = this.parentNode.parentNode;
revisionId = revision.cells[1].innerHTML.replace( /[^\d.]/g, '' );
(cause I wanna get the int of the string)
iRevisionId = parseInt(revisionId);
Is there a more proper way to do it, with the given className ?
Because in the case where someone adds a cell before mine in the future, my code is going to be "deprecated".
Hope i've given all the details,
Thanks by advance.
// More Details //
The problem with most answers is that they work only if I have 1 <tr>. Once I get multiple, it gets every revisionID like this :
console.log(result) -> #1#2#3#4
(if I have 4 <tr> for exemple)
So this is why I am getting the GOOD one like this :
revision = this.parentNode.parentNode; // outputs the good <tr>
but after that, I can't get the with the given className.
if this is tr
var data = $(this).children(".revision_id").text()
Using the text() method, you can get the text inside your td element.
After that just parse it like you did with parseInt()
$(function() {
var quantity = $('tr td.quantity').text();
console.log(parseInt(quantity));
});
you can do via jquery like this:
var value= parseInt($(".vision_id").text().match(/[0-9]+/g)[0]);
FIDDLE EXAMPLE
Depends on whether you can use jQuery or not.
Pure JavaScript
With pure JS, provided you're using a modern browser, you can use the getElementsByClassName function. For the purpose of this demonstration, I've assumed you have an ID on your table you can use.
var myClassName = 'revision_id';
var table = document.getElementById('mytable');
// the desired TD
var td = table.getElementsByClassName( myClassName ) );
See Mozilla's docs on getElementsByClassName.
Also, this answer works with backwards compatibility.
jQuery
Of course, this becomes easier with jQuery:
var $td = $('#mytable td.revision_id');
Demo here: http://jsfiddle.net/uJB2y/1/
Well if you want it with jquery then you can use .filter() method:
var text = $('td').filter(function () {
return this.className === 'revision_id';
}).text().slice(1);
text = +text; // conversion for int
alert(text);
Demo
I have a page with 2-3 tables. In those tables I want to change the text of a specific column located in <thead> and also a value in each <td> line, and I would like to get the id from each line.
What is the fastest way to do this, performance-wise?
HTML
Table-Layout:
<table class="ms-viewtable">
<thead id="xxx">
<tr class ="ms-viewheadertr">
<th>
<th>
<tbody>
<tr class="ms-itmHover..." id="2,1,0">
<td>
<td>
<tr class="ms-itmHover..." id="2,2,0">
<td>
<td>
</table>
JavaScript
Script with that I started:
$('.ms-listviewtable').each(function () {
var table = $(this);
$table.find('tr > th').each(function () {
//Code here
});
$table.find('tr > td').each(function () {
//Code here
});
How can I get the Id? Is this there a better way to do what I want?
You can get the id of an element by calling .attr on "id" i.e. $(this).attr("id");.
In jquery the best way to get to any element is by giving it an ID, and referencing it.
I would structure it the other way around - give the table elements meaningful IDs, and then put the information that I'd like to retrieve in their class attributes.
<tr id="ms-itmHover..." class="2,2,0">
And then retrieve it as follows: $('#ms-itmHover...').attr('class');
You can get the IDs by "mapping" from table row to associated ID thus:
var ids = $table.find('tbody > tr').map(function() {
return this.id;
}).get();
You can access individual cells using the .cells property of the table row:
$table.each('tbody > tr', function() {
var cell = this.cells[i]; // where 'i' is desired column number
...
});
Go thru all tables, collect all rows and locate their identifiers by your needs:
$('table.ms-viewtable').each(function(){
$(this).find('tr').each(function(){
var cells = $(this).children(); //all cells (ths or tds)
if (this.parentNode.nodeName == 'THEAD') {
cells.eq(num).html('header row '+this.parentNode.id);
} else { // in "TBODY"
cells.eq(num).html('body row '+this.id);
}
});
});
jsfiddle
I got a table:
<table id="ItemsTable" >
<tbody>
<tr>
<th>
Number
</th>
<th>
Number2
</th>
</tr>
<tr>
<td>32174711</td> <td>32174714</td>
</tr>
<tr>
<td>32174712</td> <td>32174713</td>
</tr>
</tbody>
</table>
I need the values 32174711 and 32174712 and every other value of the column number into an array or list, i'm using jquery 1.8.2.
var arr = [];
$("#ItemsTable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
See this link for demo:
http://jsfiddle.net/CbCNQ/
You can use map method:
var arr = $('#ItemsTable tr').find('td:first').map(function(){
return $(this).text()
}).get()
http://jsfiddle.net/QsaU2/
From jQuery map() documentation:
Description: Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
.
As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.
// iterate over each row
$("#ItemsTable tbody tr").each(function(i) {
// find the first td in the row
var value = $(this).find("td:first").text();
// display the value in console
console.log(value);
});
http://jsfiddle.net/8aKuc/
well from what you have, you can use first-child
var td_content = $('#ItemsTable tr td:first-child').text()
// loop the value into an array or list
http://jsfiddle.net/Shmiddty/zAChf/
var items = $.map($("#ItemsTable td:first-child"), function(ele){
return $(ele).text();
});
console.log(items);