I have some divs on a page in this order as below. When someone clicks a link inside the UL .list-links I want to capture the value of
<span class="asa_portlet_title">Title here</span>
in a variable. I've tried using siblings and closest but it always returns empty.
--
<div class="my_portlet" style="display:none;">
<span class="asa_portlet_title">Title here</span>
</div>
<div class="links">
<div class="">
<ul class="list-links">
<li class="margin-bottom-medium">
<a href="linkhere.html" target="_self">Link name</a>
<a href="linkhere.html" target="_self">Link name</a>
<a href="linkhere.html" target="_self">Link name</a>
<a href="linkhere.html" target="_self">Link name</a>
</li>
</ul>
</div>
</div>
--
$('[ul.list-links a').click(function() {
var _portletTitle = $(this).siblings('.my_portlet').text();
});
Open to pure javascript method as well. Basically I have a number of divs on the page containing links, and those divs have another div above it where the title exists
Would anyone be able to put together a small working sample?
You are not trying to get the siblings, you are trying to get the sibling of the parent .links
of this
.
Also you have to prevent the default action of the a element. You can do that by calling preventDefault()
on the event object.
$('ul.list-links a').click(function(event) { event.preventDefault(); var _portletTitle = $(this).closest('.links').prev('.my_portlet').text(); console.log(_portletTitle); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="my_portlet" style="display:none;"> <span class="asa_portlet_title">Title here</span> </div> <div class="links"> <div class=""> <ul class="list-links"> <li class="margin-bottom-medium"> <a href="linkhere.html" target="_self">Link name</a> <a href="linkhere.html" target="_self">Link name</a> <a href="linkhere.html" target="_self">Link name</a> <a href="linkhere.html" target="_self">Link name</a> </li> </ul> </div> </div> <div class="my_portlet" style="display:none;"> <span class="asa_portlet_title">Title here 2</span> </div> <div class="links"> <div class=""> <ul class="list-links"> <li class="margin-bottom-medium"> <a href="linkhere.html" target="_self">Link name 2</a> <a href="linkhere.html" target="_self">Link name 2</a> <a href="linkhere.html" target="_self">Link name 2</a> <a href="linkhere.html" target="_self">Link name 2</a> </li> </ul> </div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.