I'm working on an app where I need to clone a table, then access the td and tr independently, depinding on their attributes or classes within this table.
Is there an easy way to accomplish this with the classical jQuery selector or do I need to write a whole new function ?
Code :
JS
var grid = $("table").clone();
console.log($(grid).$("td"));
Assuming you're starting with just one table, the following selector string will find all the rows in that table (as you know).
$("table tr")
but if you're referencing your table with a variable you have to use the find operator with the remainder of the original selector string instead, e.g.
var $table = $("table");
$table.find("tr")
I'm prefixing my variable with a $ as a note-to-self that it's already a jQuery object, i.e. there's no need to $($table).
You can work with the clone in exactly the same way:
var $clone = $("table").clone();
$clone.find("tr")
Yes you can use the clone just like a regular jQuery selector. For your example it would be
var grid = $("table").clone();
console.log($(grid).find("td"));
or even
console.log(grid.find("td"));
Related
I need to get the number of rows in a table using a variable as the table selector. I get the table with this:
var table_element = $(this).prev('table.w2bw2c-with-artists-table');
I tried this from a previous post but got an error that length was undefined.
var new_with_artist_index = $(table_element).rows.length;
I have seen these methods used to find the number of rows in a table:
var rowCount = $("#tblEmployee td").closest("tr").length;
var rowCount = $('#myTable tbody tr').length;
How can I use one of these methods where the table selector is a variable instead of an ID? Or is there a better way?
You can just use .find() method on jQuery object.
var rowCount = table_element.find('tbody tr').length;
Or, You could get the native table using [] or .get() then use .rows property
var rowCount = table_element[0].rows.length;
var row = $("#tblEmployee td").find("tr");
var rowCount = row.length;
Many ways to do this:
1. jQuery find method
$(tableElement).find('tr').length
2. jQuery context parameter (i call it that way)
$('tr', tableElement).length
3. Plain Javascript
tableElement.querySelectorAll('tr').length
As you see the shortest would be the second variant, i think its also very clear, so if you can utilize jQuery, go for that variant. If you dont have jQuery in your library yet you should probably use the third variant.
querySelectorAll is defined for all DOM Elements and returns a NodeList. There is also a querySelector function, that will return the first match of the selector (so a single Element or null if nothing matches).
NodeList does not extend Array, so if you want to iterate the list, you need to do it that way:
[].forEach.call(tableElement.querySelectorAll('tr'), function(element) {
doSomething();
});
I found an answer from Ricky G at
jQuery: count number of rows in a table
Here's my code:
//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
return $('tr', $(this).find('tbody')).length;
};
To use:
var table_element = $(this).prev('table.w2bw2c-with-artists-table');
var new_with_artist_index = $(table_element).rowCount();
Thanks and a tip of the hat to Ricky G!
How can I directly select classes, etc using a variable?
var $tbody = $(".tbl-locations-body");
$(".tbl-locations-body a.collapse").hide();
$(".tbl-locations-body tr.child-row").hide();
$(".tbl-locations-body .container").first().hide();
$(".tbl-locations-body .tab-content").hide();
I want to use $tbody to perform the methods. What is the syntax?
You could use the find() method from the $tbody jQuery object. Note that you can apply multiple selectors as well to make the calls a one-liner:
var $tbody = $(".tbl-locations-body");
$tbody.find('a.collapse, tr.child-row, .container:first, .tab-content').hide();
var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();
// etc...
Explanation:
If you pass $tbody as second parameter into jquery function, you will search only in a scope of that element($tbody), rather than in whole document.
You can use the find() method - see code below:
var $tbody = $(".tbl-locations-body");
$tbody.find("a.collapse").hide();
$tbody.find("tr.child-row").hide();
$tbody.find(".container").first().hide();
$tbody.find(".tab-content").hide();
I've been reading up on this and although
var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();
looks cleaner, under the hood it's changed to $tbody.find() anyway. So the better answer is to use the find method to start with - and as Rory pointed out, you can select multiple too.
I have a string containing html elements, now I need to select some elements and remove them from the string.
In JQuery I tried the following:
html_string = "<ul><li data-delete>A<li><li>B</li></ul>";
html_clean_string = $(html_string).remove('[data-delete]').html();
This is what I expected:
"<ul><li>B</li></ul>"
But I got the same original string. So how can I use CSS selectors to remove html elements from a string?
You can do it like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var elems = $(html_string);
elems.find('[data-delete]').remove();
var html_clean_string = elems[0].outerHTML;
You had a couple of issues:
.remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.
Since you want the host top level HTML too, you will need the .outerHTML.
You had mistakes in your html_string.
Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/
You can also save a little jQuery with more chaining like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerHTML;
Working jsFiddle:http://jsfiddle.net/jfriend00/wmtascxf/
Having a table like:
<table id="table_1">
<tr><td>1</td><td>foo</td></tr>
<tr><td>2</td><td>foo</td></tr>
<tr><td>3</td><td>foo</td></tr>
<tr><td>4</td><td>foo</td></tr>
</table>
I want to get the first td of each table row.
Then i want to iterate through the findings and compare the text value contained in the td with a value i have.
So far, i can get the first td of each tr by using the following :
var test = $("#table_1").find('td:first-child');
Then i get the number of tds : console.log(test.length);
but when i try to get the text of a td i get an error : console.log(test[1].text());
Error:
Uncaught TypeError: test[1].text is not a function
Obviously i do something wrong. Is my way of thinking wrong? How can i fix it?
test is jquery object of all first child elements. You should be using .eq(0) or .first() to target first element in the collection:
console.log(test.eq(0).text());
or
console.log(test.first().text());
Update: To get all the texts of first-child td elements in array
var allfirsttdtext = test.map(function(){
return $(this).text();
}).get();
Working Demo
test[1] will return underlying DOM element and .text() is a jQuery function thus you are getting the error.
I think, You need to use .eq()
Reduce the set of matched elements to the one at the specified index.
Code
test.eq(0).text()
Note: that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.
OR, Use textContent
test[1].textContent
use textContent in JavaScript bcoz u are converting jquery object into javascript object
console.log(test.eq(0).text());
or
console.log(test[0].textContent);
You have to surround by jQuery as the resulted array is a Dom Elements:
for(i = 0; i < test.length; i++){
console.log($(test[i]).text())
}
Try this:
var v = 'compare';
$('#table_1 td').each(function () {
if ($(this).text() == v)
console.log($(this).text()+' is equal with the variable '+v);
})
console.log(test[1].text());
test -> is an array of htmlDomElement
when you say test[1] -> it gives you a htmlElement not a jQuery object of that element, so you can not use .text() which is jQuery function.
Wrap it with $(test[1]).text() to make it jQuery object to use text() function on it.
If you execute in the console on this page
var cloned = $(".question").clone(true);
$(".question").addClass("first");
var clonedStr = cloned[0].outerHTML || new XMLSerializer().serializeToString(cloned[0]);
$(".question").after(clonedStr);
you will clone the question (there will be two questions on the page, but the first one will be with the .first class). That's what is needed.
Is there any simpler way to do this with jQuery? I'm confused of the third string in the code above and believe it could be simpler. Any ideas?
Thank you.
If you don't use the HTML as string, then don't get it. Just use the jQuery object:
var cloned = $(".question").clone(true);
$(".question").addClass("first").after(cloned);
Also, you can do it one line:
$(".question").after($(".question").clone(true)).first().addClass("first");
You could use insertAfter to insert the cloned element after changing the class. You don't need to convert the element in the jQuery object to a string, you can use that object within the function itself:
var $question = $('.question');
var $cloned = $question.clone(true).insertAfter($question);
$question.addClass('first');