jquery how to get the parent text using chlid?
html, javascript, jquery
Solution
you can try like this
$("button").click(function(){
alert($(this).parent('div').parent('div').children('p').text())
})
<div>
<p>parent p1</p>
<p>parent p2</p>
<div id="sub">
<p>child div</p>
<button type ="button">click</button>
</div>
</div><script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Problem
I need to get the text of the `<p>` tag that is in the parent div only and not from the child div.I have tried the following code which get all text in both parent and child div. Note:I need to get the text parent p1 and parent p2 only Downvoters plz mention the reason so that i cannot make that mistake in future Html ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <p>parent p1</p> <p>parent p2</p> <div id="sub"> <p>child div</p> <button type ="button">click</button> </div> </div> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ var a = $(this).parent("div").attr("id"); console.log($("#"+a).parent("div").text()); }); }); </script> ```