I have 2 div and they have the same class "meal". When I press the add button in the second div , it chooses the first title of the first div I want each div of the same class to choose their children
let meal = document.querySelector(".meal");
let tit = meal.childNodes[3];
$(".btnAdd").on("click", function() {
console.log(tit.innerText);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="meal">
<img src="" height="250" width="500" class="mealImg">
<h4 class="title">Title</h4>
<button class="btnAdd">Add</button>
<i class="far fa-heart" id="favIcn"></i>
</div>
<div class="meal">
<img src="" height="250" width="500" class="mealImg">
<h4 class="title">Title</h4>
<button class="btnAdd">Add</button>
<i class="far fa-heart" id="favIcn"></i>
</div>
Since you're already using jQuery, why not use it across the board and leverage the use of siblings()?
$('.btnAdd').on('click', function() {
console.log($(this).siblings('.title').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="meal">
<img src="" height="250" width = "500" class="mealImg">
<h4 class = "title">Title</h4>
<button class="btnAdd">Add</button>
<i class="far fa-heart" id="favIcn"></i>
</div>
<div class="meal">
<img src="" height="250" width = "500" class="mealImg">
<h4 class = "title">Title 2</h4>
<button class="btnAdd">Add</button>
<i class="far fa-heart" id="favIcn"></i>
</div>