javascript - jQuery - Get nearest element with class -
i have mess html code , cant influence structure.
<div class="head"> <p class="any">something 1</p> </div> <input type="text" class="mand" value="1"> <div class="head"> <p class="any-else">something 2</p> </div> <div class="foo"> <input type="text" class="mand" value="2"> </div> <div class="head"> <p class="any">something 3</p> </div> <div class="foo"> <div class="another-needless-div"> <input type="text" class="mand" value="3"> </div> </div>
i need every input class "mand" next above text p in head-div. example: input field value"3", need p text "something 3".
$(".mand").each(function(){ console.log( $(this).prev(.head).find('p').text() ); // not working });
how can content? thank you!
you can try this, loop through each parent until has prev element class head
function parent(obj) { if ($(obj).prev(".head").length) { return $(obj).prev(".head").find("p").text() } else { return parent($(obj).parent()) } } $.each($('.mand'), function() { console.log(parent($(this))); })
function parent(obj) { if ($(obj).prev(".head").length) { return $(obj).prev(".head").find("p").text() } else { return parent($(obj).parent()) } } $.each($('.mand'), function() { console.log(parent($(this))); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="head"> <p class="any">something 1</p> </div> <input type="text" class="mand" value="1"> <div class="head"> <p class="any-else">something 2</p> </div> <div class="foo"> <input type="text" class="mand" value="2"> </div> <div class="head"> <p class="any">something 3</p> </div> <div class="foo"> <div class="another-needless-div"> <input type="text" class="mand" value="3"> </div> </div>
Comments
Post a Comment