Jquery Finding the closest link? - javascript

I want to be able to get the href from this type of code:
<tbody>
<tr class="odd">
<td class=" sorting_1">
The Link Text
</td>
</tr>
</tbody>
but I want to be able to click on the link itself, or the td.
Here is my CoffeeScript:
$("#myID tr td").click (event)->
event.preventDefault()
link = $(event.target).find("a").attr("href")
$("#anAjaxPod").load(link)
This works if one clicks on the td, but not if if one clicks on the link.
Edit: Updated question, I used find at first. This is just the last code I played with

Use .find() ; .closest() is to climb up the DOM tree testing self and ancestors. Here anchor tag is the child of td so you need to descend down. So find or a children selector is what you need.
$(this).find("a").attr("href")
Closest get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
$("#myID tr td").click(function(event){
event.preventDefault()
link = $(this).find("a").attr("href");
$("#anAjaxPod").load(link);
});
Fiddle

.closest() looks and self or ancestors where as you want to descendent, to find the descendent use find()
link = $(event.target).find("a").attr("href")

try this:
$(function(){
$("#myID tr td").click(function(){
Link = $(this).find("a").eq(0).attr("href");
$("#anAjaxPod").load(Link);
return false;
})
})

Related

Get dynamic class of element in javascript

I have a table with a bunch of tr elements with random, dynamically created ids, and corresponding divs with matching ids. I want to use the on('click') function so that when one tr element with a given id is clicked, the corresponding div id is also clicked via javascript.
The table:
<tbody>
<tr id="a94k5h3"></tr>
<tr id="0f3l6k2"></tr>
<tr id="44jg96a"></tr>
</tbody>
The divs:
<div id="a94k5h3"></div>
<div id="0f3l6k2"></div>
<div id="44jg96a"></div>
The code I have so far:
$(document).on('click', '#view_347 #a94k5h3', function(event) {
event.preventDefault();
$("#view_349 .kn-view.kn-map-results.view_349 #a94k5h3").click();
});
The above code works for the first one, but in practice I won't know what the id #a94k5h3 is, or how many tr/divs there will be. Any help would be much appreciated!
-Edit
I am using knack, which creates all of the html elements dynamically, it is not my code. I have attached an image of the output for possible clarification.
[![enter image description here][1]][1]
Essentially I have the same html element on a page twice. When one is clicked, I want the other one to be clicked too.
Since you cannot have duplicate ID on a single page what I suggest you is to use the data-* attribute like this:
<tr data-id="#a94k5h3">
and use .trigger("click") to trigger the designated click event on the DIV
Elements
Example:
$(document).on('click', '[data-id]', function(event) {
event.preventDefault(); // not sure you need this...
// ID is unique! remember? you don't need the classes extra selectors
// Use trigger "click"
$($(this).data("id")).trigger("click");
});
// Just to test!:
$("#view_349").find("div").on("click", function() {
console.log( this.id );
});
<table>
<tbody>
<tr data-id="#a94k5h3"><td>a94k5h3 CLICK ME</td></tr>
<tr data-id="#0f3l6k2"><td>0f3l6k2 CLICK ME</td></tr>
<tr data-id="#44jg96a"><td>44jg96a CLICK ME</td></tr>
</tbody>
</table>
<div id="view_349">
<div id="a94k5h3">DIV a94k5h3</div>
<div id="0f3l6k2">DIV 0f3l6k2</div>
<div id="44jg96a">DIV 44jg96a</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You shouldn't have duplicate id's in your dom, instead you should have data-* attributes. I chose data-id, but what you can do is grab the id of the clicked row, then do a selection based on that, it would look something like this:
$(document).on('click', 'tr', (event) => {
event.preventDefault()
let id = $(event.currentTarget).attr('id')
$(`[data-id=${id}]`).addClass('selected').click()
})
tr {background-color: red}
div.selected {background-color: yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="a94k5h3"><td>Click Me</td></tr>
<tr id="0f3l6k2"><td>Click Me</td></tr>
<tr id="44jg96a"><td>Click Me</td></tr>
</table>
<div data-id="a94k5h3">1</div>
<div data-id="0f3l6k2">2</div>
<div data-id="44jg96a">3</div>
Adding TR element click handlers, to click a corresponding DIV element, needs a query selector that does not involve unknown random id values. E.G.based on the console log image:
"#view_349 table.kn-table TBODY TR"
I assume the selector for the DIV element works as provided
"#view_349 .kn-view.kn-map-results.view_349 #" + divId
Then the TR element click listener function can use the id of the TR element clicked,
event.target.id
to find the corresponding DIV element using JQuery:
$(document).on('click', "#view_347 TR" function(event) {
event.preventDefault();
var targetId = event.target.id;
$("#view_349 .kn-view.kn-map-results.view_349 #" + targetId).click();
});
This will probably work in JQuery but ignores the fact that having two elements with the same id is not valid HTML, as discussed in this question and previously mentioned in comments and other answers. I recommend looking into the possibility of generating the HTML without repeating exactly the same element id value.

Really next element with specific class

I am newbie in Jquery, sorry for my silly question.
Here is my HTML code :
<tr role="row" class="odd">
<td><input type="checkbox" class="mycheckbox" value="2166"></td>
<td class="sorting_1">2166</td>
<td><span class="myparentid">743</span>
</td><td>0</td>
</tr>
I would like to jump from 'mycheckbox' element to 'myparentid' element, ignoring the tree structure.
In Jquery, I tried something like :
var checkedRow = $(".mycheckbox");
var nextelem = checkedRow.next(".myparentid");
It does not work because next searches only in siblings...
Can you give me a hint ?
Thanks !
The easiest option is to go up to a common parent element (in this case the table row), then back down to the one you want:
$(".mycheckbox").closest("tr").find(".myparentid")
https://api.jquery.com/closest/
https://api.jquery.com/find/
Edit: To add some additional information:
$(".mycheckbox")
is the starting location, it's at: tr>td>input.mycheckbox
(where > means directly below in the html tree)
.closest moves up the tree until it finds a matching parent element, so .closest("tr") will find
<tr role="row" class="odd">
by looking at the direct parent "td", then it's direct parent "tr".
Normally I'd use a class here (<tr class="businessobjectcontainer">) (depending on what the business object is) then it can be a div or tr if you change this part of it later and seeing .odd I'd assume this is for styling and there'll be a .even - so that's not ideal as a selector. So "tr" would have to do.
.find() does the opposite of .closest and goes down the tree looking for a matching element, in this case .myparentid will find: tr>td>span.myparentid
which is what you're looking for.
.find() may not be the most efficient, but it's probably the most flexible as it means you can move the content of your tr around as much as you like.
A move efficient alternative might be to use:
$(">td>span.myparentid", $(".mycheckbox").closest("tr"))
but mostly it's just changing the syntax.

Change text of specific <a> text using jQuery

I have an asp:Repeater that makes a table with a few <td>s and <tr>s. In each of the <tr>s, I have an <a></a>.
Now, on a certain event I want to change just the <a></a> tag in the <tr>.
So, I want to do something like:
$("a").text("I changed!");
, but I only want to change the <a>.text in one <tr>, not all the <a> elements on the page.
I am experimenting with .closest(), but unfortunately don't know enough about jQuery to make this functional.
if you have the target tr somehow, then you can use the following code to find the a tag inside that:
tr.find("a").text("text here");
How to find tr really depends on what context you are in and how your target tr is identified from others.
e.g. if it's the "first" tr you may say:
var tr = $("tr").first();
if it's the element that the event has happened for (e.g. click event):
var tr = $(this);
if you are in the event of a child element of target tr you may say:
var tr = $(this).closest("tr");
You should mark the <tr> with an Id so that you could identify it and then change the containing
So for example you could mark your <tr> with id 'myid' and do something like this in jquery:
$("#myid a").text("I changed!");
Or if you dont want to mark it with an Id then, you could use selectors if you know which it is.
For example getting the first would be:
$("tr:first a").text("I changed!");
Some references:
http://api.jquery.com/first-selector/
http://api.jquery.com/category/selectors/

jQuery.closest() gives "null" value

I am doing with this plugin :
<table>
<tr>
<td>
<a class="linkType1" href="google.com">
Google
</a>
<span style="display: none;">Goooooooooooogle</span>
</td>
</tr>
<tr>
<td>
<a class="linkType1" href="yahoo.com">
Yahoo
</a>
<span style="display: none;">Yaaaaaaaaaaaaaaho</span>
</td>
</tr>
</table>
How can I select the closest span of linkType1-anchors for displaying as tooltip ?
Currently I am doing :
jQuery(document).ready( function() {
jQuery("a.linkType1").tooltip({
bodyHandler: function() {
alert(jQuery(this).closest("span").html()); // this alert is showing `null`
return "hi"; // i need to setup the alerted content here
},
showURL: false
});
});
Your span elements aren't ancestors of the links, so closest (which looks for a match for the selector on the current element or its ancestors) isn't what you're looking for.
Based on your markup, you might want next("span") (which will find the next sibling, but only if it's a span; it doesn't continue with subsequent siblings) or possibly nextAll("span").first() (which will find the first next sibling that's a span, in case you ever put something between the a and the span), which finds all subsequent siblings with nextAll and then grabs the first of them (the one nearest the link) via first. So
// If the `span` will always be the very next sibling
alert(jQuery(this).next("span").html());
or
// If you may put something between the `a` and the `span` at some point
alert(jQuery(this).nextAll("span").first().html());
closest() finds the closest parent element. You are looking for a sibling:
jQuery(this).next("span").html()
$(this) is referring to bodyHandler function.
Try this
alert(jQuery(linkType1).closest("span").html());
Why not use find() instead? As closest() transverses up the DOM tree

How to get inner tr tag using JQuery?

I am trying to grab documentnumber attribute from the tr tags inside tbody, and save it in an array.
Below is the html , I am working on
<tbody class="line-item-grid-body">
<tr data-group-sequence-number-field-index="" data-sequence-number-field-index="1" documentnumber="80" documentid="4133604" parent="80" class="line-item parent-line-item line-item-show reorderable-row droppable-element">
<td>
<table>
<tbody>
<tr></tr>
</tbody>
</table>
</td>
</tr>
<tr data-group-sequence-number-field-index="" data-sequence-number-field-index="1" documentnumber="80" documentid="4133604" parent="80" class="line-item parent-line-item line-item-show reorderable-row droppable-element">
</tr>
</tbody>
and this is what I did, which is not working. If I don't specify particular class then system also grabs inner tr tags, which I don't want
var docs = jQuery("#line-item-grid").find('tbody').find("tr[class='line-item parent-line-item line-item-show reorderable-row droppable-element']");
for (i=1;i<=docs.length;i++)
{
var tempValue = jQuery(docs[i]).attr('documentnumber');
alert(tempValue);
}
Any ideas?
There's several ways you could go about this. I would do the following....
var docs = $('.line-item-grid-body>tr');
Docpage: Child selector
Another option:
var docs = $('.line-item-grid-body').children('tr');
Bookmark and frequent this page ... Selectors - jQuery API
try this as your selector
$('tbody > tr','#line-item-grid');
Hmm i didn't test this (so check for typos), but off top of my head, i'd try something like this:
jQuery(".line-item-grid tbody > tr").each(function() {
alert($(this).attr('documentnumber');
});
You can define selectors one after another, pretty much same as in CSS.
Also check child selector (http://api.jquery.com/child-selector/) for selecting direct child elements.
Hope it helps

Categories