jas jas - 1 month ago 8
Javascript Question

How to get text for div close to button clicked

I'm trying to get the text of some div within the parent div where button is clicked. This is an example code

<div class="parentDiv" >
<div id="divToFind" style="display:none">text</div>
<div class="btn-group">
<button class="button" type="button" >Remove</button>
</div>
</div>

<div class="parentDiv" >
<div id="divToFind" style="display:none">text2</div>
<div class="btn-group">
<button class="button" type="button">Remove</button>
</div>
</div>


Here parentDiv is repeated couple of times and text of divToFind is different in each parentDiv. Whenever remove button is clicked within the parentDiv I want to get the text of divToFind.

I have tried this

$(this).closest('.parentDiv').children('#divToFind').text();


But nothing is returned

Answer

Don't use same IDs in a single document. You should use classes instead. With class, it works fine.

It is mentioned in the spec that there must not be multiple elements in a document that have the same id value.

$(function(){
  $("button").on("click", function(){
    var t = $(this).closest('.parentDiv').children('.divToFind').text();
    console.log(t);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentDiv" >
    <div class="divToFind" style="display:none">text</div>
    <div class="btn-group">
        <button class="button" type="button" >Remove</button>
    </div>
</div>                 
<div class="parentDiv" >
    <div class="divToFind" style="display:none">text2</div>
    <div class="btn-group">
        <button class="button" type="button">Remove</button>
    </div>
</div>