Reputation: 3462
How can I get from function (e)
the contents of parents, namely #message
and #date
?
JQuery
$(document).ready(function () {
$(document).on('click', '#quote', function (e) {
// How to get here content of #message, #date of that div where Quote was clicked?
// Example "PostNumber 751883","7/31/2009 12:00:00 AM"
});
});
HTML
<ul>
<li>
<div class="flexbox-container">
<div class="flexbox-date">
<div class="topic-header">
<div class="date-item">
<div style="display: flex">
<div style="align-self: center" id="date">
7/31/2009 12:00:00 AM
</div>
<div style="align-self: center">
<a id="quote" class="btn btn-light btn-sm">Quote</a>
</div>
</div>
</div>
</div>
</div>
<div id="message" class="flexbox-message">PostNumber 751883</div>
</div>
</li>
<li>
<div class="flexbox-container">
<div class="flexbox-date">
<div class="topic-header">
<div class="date-item">
<div style="display: flex">
<div style="align-self: center" id="date">
7/22/2009 12:00:00 AM
</div>
<div style="align-self: center">
<a id="quote" class="btn btn-light btn-sm">Quote</a>
</div>
</div>
</div>
</div>
</div>
<div id="message" class="flexbox-message">PostNumber 743123</div>
</div>
</li>
</ul>
Upvotes: 0
Views: 40
Reputation: 2147
You may use the id
of an html tag only once per page. Addtionally you should put your inline style
s into css files if possible.
I modified your html with classes and you can try the following jQuery as well.
$(document).ready(function() {
$('.quote').on('click', quoteClick);
function quoteClick(event) {
var parent = $(event.target).closest('li');
if (parent.length) {
var date = parent.find('.date').text();
var message = parent.find('.flexbox-message').text();
console.log(date);
console.log(message);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<div class="flexbox-container">
<div class="flexbox-date">
<div class="topic-header">
<div class="date-item">
<div style="display:flex; ">
<div style="align-self: center;" class="date">
7/31/2009 12:00:00 AM
</div>
<div style="align-self: center;">
<a class="btn btn-light btn-sm quote">Quote</a>
</div>
</div>
</div>
</div>
</div>
<div class="flexbox-message">
PostNumber 751883
</div>
</div>
</li>
<li>
<div class="flexbox-container">
<div class="flexbox-date">
<div class="topic-header">
<div class="date-item">
<div style="display:flex;">
<div style="align-self: center;" class="date">
7/22/2009 12:00:00 AM
</div>
<div style="align-self: center;">
<a class="btn btn-light btn-sm quote">Quote</a>
</div>
</div>
</div>
</div>
</div>
<div class="flexbox-message">
PostNumber 743123
</div>
</div>
</li>
</ul>
Upvotes: 0
Reputation: 223
You need to get its parent element up to <li>
tag from there, find the #message
and #date
elements
use closest:
console.log($(this).closest('li').find("#date").text())
console.log($(this).closest('li').find("#message").text())
just trim it.
Upvotes: 1