I am trying to get the value of very next element of the current/selected element for example here is the list
<ul>
<li class="abc selected"><a href="www.test.com">test</a> </li>
<li class="abc"><a href="www.test1.com">test1</a> </li>
<li class="abc"><a href="www.test2.com">test2</a> </li>
</ul>
From the above code I am trying to get the value of "a" tag which is very next to the selected li, in above case I am try to get the value of a tag which is test1 and this "a" tag is within the very next li after the selected one.
I tried to use the jQuery below but its fetching the empty result. Any help
var linktext1= jQuery(".selected").next("li a").text();
alert (linktext1);
The selector string passed to .next will filter out the next element if it doesn't match the selector string. But the next element is a li, not an a, so .next('li a') won't work.
Use .next("li").find('a') instead:
var linktext1 = jQuery(".selected").next("li").find('a').text();
console.log(linktext1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="abc selected"><a href="www.test.com">test</a> </li>
<li class="abc"><a href="www.test1.com">test1</a> </li>
<li class="abc"><a href="www.test2.com">test2</a> </li>
</ul>
In this particular situation, though, there's no need for a li selector to pass to .next, because what is .selected will be a li, so any of its siblings will also be lis:
var linktext1 = jQuery(".selected").next().find('a').text();
console.log(linktext1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="abc selected"><a href="www.test.com">test</a> </li>
<li class="abc"><a href="www.test1.com">test1</a> </li>
<li class="abc"><a href="www.test2.com">test2</a> </li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With