简体   繁体   中英

Get value of a span inside the div when other span is clicked

Here is the structure that I have:

<div class="div1">
    <span class="span1">
       <span class="span2">X</span>
       <span class="span3">some text</span>
    </span>   
</div>

Question that I have when I click on the span2 , is how to pick up via alert for example text of span3 ?

jQuery

$('.span2').on('click', function() {
    var $span3 = $(this).closest('.span1').find('.span3');

    console.log($span3.text());
});

Check Fiddle

Vanilla JS

let span2 = document.querySelectorAll('.span2');

Array.from(span2).forEach(function(elem) {
        elem.addEventListener('click', function() {
            let span3 = this.parentNode.querySelector('.span3');

            console.log(span3.innerHTML);
      });
});

Check Fiddle

You would need to target the closest parent which is span1 here that contains span3 and then get the text of that element.

Since you're using jQuery you've several choices so you could use .parents() or .siblings() or .next() or also closest() (as shown in Sushanth's answer), to target the related .span3 span :

$('.span2').on('click', function(){
    $(this).parents('.span1').find('.span3').text();
    //Or
    $(this).siblings('.span3').text();
    //Or
    $(this).next('.span3').text();
})

Hope this helps.

 $('.span2').on('click', function(){ console.log( $(this).parents('.span1').find('.span3').text() ); //Or console.log( $(this).siblings('.span3').text() ); //Or console.log( $(this).next('.span3').text() ); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div1"> <span class="span1"> <span class="span2">X</span> <span class="span3">some text</span> </span> </div>

Edit: Changed it if there are mutliple sets.

Here's a JavaScript example using .nextElementSibling property:

SNIPPET

 var d1 = document.querySelector('.div1'); d1.addEventListener('click', function(e) { var txt = e.target.nextElementSibling.textContent; alert(txt); }, false);
 .span2 { border: 1px solid black; } .span3 { pointer-events: none }
 <div class="div1"> <span class="span1"> <span class="span2">X</span> <span class="span3">some text 1</span> </span> <br> <span class="span1"> <span class="span2">X</span> <span class="span3">some text 2</span> </span> <br> <span class="span1"> <span class="span2">X</span> <span class="span3">some text 3</span> </span> <br> <span class="span1"> <span class="span2">X</span> <span class="span3">some text 4</span> </span> </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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM