I am trying to compare if the two td elements are the same within 1 table.
I have
var element = $('.table td');
$('table:odd td','.table').each(function(){
if(element.is(this)){
console.log('find')
}
)}
I want to check if the element is the same as this but my codes don't seem to work here.
Can anyone give me a hint for it? Thanks a lot
regular DOM nodes can be compared against each other, and using get(0) will get you the first DOM node from the jQuery collection :
var element = $('.table td');
$('table:odd td','.table').each(function(){
if (element.get(0) === this ){
console.log('find');
}
});
It does look like element would contain more than one element, especially as you're iterating the same selector with an added :odd on the next line, so the comparison seems a little strange, and will probably return false ?
Related
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.
I know that to hide the first element in a table is simply do (':first-child') but is there a way to specify that only the first element of the first TABLE needs to be removed?
In my situation the first element of every table is being hidden and I need to fix this.
I suppose you just target the first table, and then the first element, whatever that is ?
document.querySelector('table tr').style.display = 'none';
FIDDLE
as querySelector gets the first matching element, or in jQuery
$('table:first tr:first').hide()
FIDDLE
target the first table and the first td.
$('table:first td:first').hide()
DEMO
You can get a collection of all tables using document.getElementsByTagName("table"). Element zero of that collection ([0]) is the first table. You can then apply your first-child solution to element zero.
This does not require jQuery, nor that you assign an ID attribute to a specific table. (Assigning an ID attribute is probably more efficient if you know in advance which table is going to be first.)
Edited to add: I've tested this and it works, although it is revised from my first "it works" post. The first child element of TABLE is TBODY for a table that starts with a tr element, so what is really wanted is the first child of TBODY. It is probably better to descend the firstElementChild tree looking exspressly for a nodeName of "TR" and hide that. Look further down in this post for that approach.
Here is the simple code that works:
document.getElementsByTagName("table")[0].firstElementChild.firstElementChild.style.display = "none";
This is pure JavaScript, with no need for jQuery. Note that document.getElementsByTagName returns a live collection, so even if a table is added to the DOM, this will get the first one.
Do remember that the first element child of <table> (and then TBODY) is not necessarily <tr>. If you can be sure it is, or if you want the first element regardless, then what I've given will work for you. If you want to be sure it's a <tr> then a little more work will be needed.
This code finds and hides the first <tr> but will be less efficient because it gets two HTML collections:
document.getElementsByTagName("table")[0].getElementsByTagName("tr")[0].style.display = "none";
const tables = document.getElementsByTagName("table")
const firstTable = tables[0];
const firstRow = firstTable.rows[0];
firstRow.style.visibility = "hidden"; //hide
firstRow.style.visibility = "visible"; //visible
Here is a referrence.
I have a SQL-PHP printed table, and a select at the top of the table. The table contains contacts classified by towns.
At the beginning, the table shows all contacts. If I specify the town, I want to hide the rest.
I'm trying to use a jQuery script
<script>
function updateit(){
if ($("#table").filter("tr") === $("#selectTown").val()) $(this).show(););
else {$(this).hide();};
}
</script>
[...]
<select id="selectTown" onchange="updateit()"><option value="NY">New York</option><option value="TX">Texas</option></select>
<table id="table">
bla bla bla...
</table>
Before I tried with find() function, but with no success.
Any suggestions?
This line $("#table").filter("tr") === $("#selectTown").val() compares document elements to string, it would not work.
Simplest solution would be to do all elements hidden and than select and show all matching elements. Example:
$('tr').hide();
$('tr[value=' + $("#selectTown").val() + ']').show();
I'm not sure where you got the idea for this code, but filter() definitely doesn't do what you think it's doing. $("#table").filter("tr") is going to give you a list of tr elements in the table. That list itself isn't going to equal any selected value, it's just an array of elements.
Mocking up a few things in a jsFiddle here, perhaps you want something more like this:
$('#selectTown').change(function () {
$('#table tr').hide();
$('#table tr').filter(function () {
return $(this).find('td:first').text() === $('#selectTown').val();
}).show();
});
What this does is:
Bind to the change event of the select element (which is preferred over the inline binding you do in your markup, just in general).
Hide all of the tr elements first, you'll show the ones you want in a moment.
Show all of the tr elements which match the filter.
The filter in this case is a function which returns true if the text inside of the td element (you will likely need to update that selector) equals the selected value. The main difference here vs. what you tried is that .filter() is returning a list of matched (filtered) elements, not an actual value to compare. Internal to the filter is where the comparison takes place, in this case using a function (which needs to return true or false for any given element being filtered).
I have a website I want to take that always has the same section with the same id with all the content I want to display. I'm not very amazing at javascript and I'm wondering how I could remove everything but a specific section.
Would the best approach be to just do a loop that goes through all the elements in the DOM and remove everything but the section with the id I want to keep? If I go that approach how do I keep it from removing all the elements inside that section?
Perhaps another way to do this more efficiently would be:
document.body.innerHTML = document.getElementById( 'saveContentId' ).innerHTML
Removing one node includes all its children, so you won't need to loop over all elements in the whole document. I see two possibilities:
get the section, remove all its siblings in the current parent, and then walk up the DOM tree until document.body, while removing all siblings.
get the section and detach it from the document. Then clear document.body and re-attach the section there
The first solution seems cleaner to me, so here some sample code:
function removeEverythingBut(el) {
while (el != document.body) {
var par = el.parentNode;
for (var i=par.childNodes.length-1; i>=0; i--)
if (par.childNodes[i] != el)
par.removeChild(par.childNodes[i]);
el = par;
}
}
// usage:
removeEverythingBut(document.getElementById("my-section"));
you can save only the element you want and delete all other elements. Also I recommend using Jquery
I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.
Why wont "$(this).parent().parent()" work? What will?
Thanks,
Brendan
Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.
The best way would probably be using closest:
$(this).closest('tr');
Check out the documentation:
Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.
It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.
For example:
$(this).parents("tr:first")
Will find the closest tr "up the chain".
That should work... you might try
$(this).parents(':eq(1)');
The .parents(selector) says get all ancestors that match the selector
and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list
This snippet has performed for me in the past:
$(this).parent().parent();
Post some code for us to see if there might be another problem somewhere...
also try
$(this).closest('div.classname').hide();
If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like
$(this).parents('.myClass');
Hope this helps someone :)
Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}
.closest() is not always best option specially when you have same element construct.
<div>
<div>
<div>
</div>
</div>
</div>
You can do parent of a parent and it's very easy:
var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();
etc.