jackson jackson - 4 months ago 14
jQuery Question

How to get sibling text of element using jquery

I have

ul
list, in every
li
i have 2
span
and one a tag link and a text for li:

<li>
<span>first name 1</span>
<a>//icon to be selected</a>
<span>last name 1</span>email address 1
</li>
<li>
<span>first name 2</span>
<a>//icon to be selected</a>
<span>last name 2</span>email address 2
</li>
<!--
multiple li
-->
<li>
<span>first name n</span>
<a>//icon to be selected</a>
<span>last name n</span>email address n
</li>


Now if a user select a link in every
li
tag, by jquery i want to get
first name
and
email address
text. I will appreciate to get an answer.

Answer

Use jquery prev() and next() selector to finding target span and use nextSibling property to finding sibling text of span.

$("a").click(function(){
    var name = $(this).prev().text();
    var email = $(this).next()[0].nextSibling.nodeValue.trim();
    console.log(name);
    console.log(email);
});
a {
    color: red;
    cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>
    <span>first name 1</span>
    <a>//icon to be selected</a>
    <span>last name 1</span>
    email address 1
</li>
<li>
    <span>first name 2</span>
    <a>//icon to be selected</a>
    <span>last name 2</span>
    email address 2
</li>
<li>
    <span>first name n</span>
    <a>//icon to be selected</a>
    <span>last name n</span>
    email address n
</li>

Comments