How to get reference to the second table nested within first one (second table has no id nor class) :
<table class='top'>
<tbody>
<tr>
<td>
<table>
You can find DOM elements with functions Document.getElementsByClassName() and Element.getElementsByTagName() which return array (or better array-like object) of elements:
var table = document.getElementsByClassName('top')[0]; // or other selector
var nestedTable = table.getElementsByTagName('table')[0];
with plain javascript you can use
document.querySelector('table table') which searches for the first table element in the document, takes the found table element and searches inside it for the next table element.
if you can use jQuery just call $('table table') or $('table').next('table') its like using querySelector but returns an jQuery Object
Try document.getElementsByClassName('top')[0].getElementsByTagName('table')[0]
Related
Why does $('.classname') return just one element when it's javascript equivalent document.getElementsByClassname('classname') returns an array of elements? If it's not each other's equivalent, what is then? How to get all the element which have the same class name using jQuery? Is there any other way other than $('.classname') ?
For example,
<tr>
<td class="currentMonth">1</td>
<td class="currentMonth">2</td>
<td class="currentMonth">3</td>
<td class="currentMonth">4</td>
<td class="currentMonth">5</td>
If i use document.getElementsByClassName('currentMonth'), then I will get an array of all the elements mentioned above.
[ <td class="currentMonth">1</td>, <td class="currentMonth">2</td>, <td class="currentMonth">3</td>, <td class="currentMonth">4</td>, <td class="currentMonth">5</td> ]
But with $('.currentMonth'), I can see only one element.
How can I get all the elements using $?
The $('.currentMonth') returns a jQuery object of all the matching elements. It is wrapped in the jQuery way, but it also returns all the elements. You can get the elements by using:
$('.currentMonth').each(function () {
this; // Here this refers to each of the matched element.
});
Whereas document.getElementsByClassname('currentMonth') returns a list of DOM Objects.
So for example, if I am executing a script like this:
$('.currentMonth').html("Hello!");
All the <td>s will be changed.
$('.classname') is a jQuery Object, whereas
document.getElementsByClassname('classname') is a list of DOM Object
$('.classname') will select all the elements which matches with the class claaname and will make a jQuery Object of it.
$('.classname').html("Whatever") will remove all the .classname elements.
document.getElementsByClassname('classname')
return a NodeList object , representing collection of elements with specified class name,using browsers built-in methods while $(".className") return jQuery object and you can use jQuery methods to manipulate it
Explore More
I have a table of elements like this:
<tr id="elementId">
<img name="img" src=""/><br/>
<input name="text" type="text"/><br/>
<input name="button" type="button"/><br/>
</tr>
Each element is exactly the same, except of its id.
I try to update the elements with javascript, but I have no clue how to get the child nodes by their name.
My code:
//get element
var element = list.rows[i];
//update nodes
element.getElementByName("img")[0].src = someImg;
element.getElementByName("text")[0].value = someText;
element.getElementByName("button")[0].value = someOtherText;
The code doesn't work, because element has no function getElementByName.
Is there any other way to get the nodes by their name?
element.querySelector('[name="thename"]') or element.querySelectorAll('[name=2thename"]')
The function is getElementsByName. Elements is plural.
Note that it returns an array-like HTML Collection, so you'll need to grab the first item off it too (with [0]).
Additionally, you might find that your elements aren't actually in your table row as you are missing table cells. Validate your markup: http://validator.w3.org/nu/
In order to select all alements with a tagname in the whole document you may use
listElements = document.getElementsByTagName();
Inside a certain element, you may use
selectedElement = element.getElementsByTagName();
Notice this functions returns an array with the elements selected. If there is only one element, it will be in
listElements[0]
in the first case, or
selectedElement[0]
in the second.
I have DOM like this:
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
...
When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.
I am using this method to get the last element,but it doesn't work.
$('.add-tr').click( function() {
var last = $(this).parent().find('.child:last').attr('data');
alert(last);
})
Any idea why? Or any other suggestion to get the last element in the table?
UPDATE
Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks
Try this
var last = $(this).parent().find('.child').find('tr').last().attr('data');
In your example you get last table, but you need get last tr
Example
'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.
As there is no data attribute on <table>, .attr('data') on it will return undefined.
To get the value of data attribute on last <tr> use the selector tr:last.
var value = $(this) // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute
As the .child element is next to the button, next() can be used to get the table.child element.
var value = $(this) // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of "data" attribute
I'll recommend to use data-* attribute to store data in custom attribute.
<tr data-num="0">Foo</tr>
<tr data-num="1">Bar</tr>
And to get the value of custom data attribute use data()
.data('num')
If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().
.index()
This will return index of an element. Note that this is zero-based index which is exactly how you want.
$(".parent").click(function(){
$(this + " tr:last-child").attr("data");
});
should do.
Your code was almost correct, you missed tr:last , i.e.:
var last = $(this).parent().find('.child tr:last').attr('data');
DEMO
http://jsfiddle.net/tuga/vr1knxqq/3/
$('.add-tr').click( function(event) {
var last = $(event.target).next().find("tr").last().attr("data");
alert(last);
})
fiddle-example
You can get an array of the tr elements by using find('.child tr')
and to get the last element in that array you can use last().
Putting it all together you have this:
$('.add-tr').click( function() {
var lastTr = $(this).parent().find('.child tr').last(),
lastData = $(lastTr).attr('data');
alert(lastData);
});
I have setup a codepen here http://codepen.io/anon/pen/aOzmKg to show this working.
I am trying to select array of "tr" based on "td" class, once I got the array I want to get array of all tr's custom "data-fid" value.
This what I got,
var rows = $("#tableB tr").children(".New.selected") // returns td, but I want tr
Once I got rows, I want to get array of there data-fid values,
var selectedValues = rows.attr('data-fid'); // not sure if it will work but i guess this is how i would do it
I am trying to google but my luck with finding right wording is just failing badly todya.
<table id="tableB" class="dmctable2">
<tr data-fid="1" Class="selected"><td></td><td></td><td class="New selected"></td></tr>
<tr data-fid="2"></tr>
<tr data-fid="3" Class="selected"></tr>
</table>
you can use :has() selector for that.
Selects elements which contain at least one element that matches the specified selector.
Like this:
$("#tableB tr:has(.New.selected)")
and to get the data values in array:
$("#tableB tr:has(.New.selected)").map(function(){return $(this).data("fid");}).get();
An other alternative which is faster would be to select the .New.selected element and then access to its parent:
$("#tableB tr .New.selected").parent('tr')
I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).
the alert says tID is undefined.
javascript:
function (msg) {
var tID = $("table", msg).attr('id');
alert(tID);
$("#reloadme_"+tID).html(msg);
}
html:
<div id="reloadme_2036">
<table id="2036" class="customCSSclass">
...table contents...
</table>
</div>
Where have I gone wrong?
find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:
$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it
Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]
Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.
Maybe this is what you're looking for?
function reload(msg) {
var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
alert(tID); //alerts 2036
$("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');
If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.
Check out the JSFiddle.
You have to try like this
var msg='<table id="2036" class="customCSSclass"></table>';
alert($(msg).attr("id"));