I have the following HTML structure
<div class="container">
<div class="item"></div>
<div class="item"></div>
<div class="desc"></div>
<div class="item"></div>
<div class="item"></div>
<div class="desc"></div>
<div class="item"></div>
<div class="item"></div>
<div class="desc"></div>
</div>
For every n number of items there will be a div with a class of .desc
, where the content of a data attribute from a previous .item
is inserted.
Essentially, if you click an item it should always push the data attribute content to the next .desc
(not necessarily the nearest).
The closest I've got to achieving what I want is:
$(this).next().siblings('.desc').show().html(data);
(where $this
is the .item from the click function).
However, this pushes the content in to every .item
div, and not just the next.
You're looking for nextAll(selector).first()
:
$(this).nextAll(".desc").first().show().html(data);
(I've used .desc
rather than .person-desc
as the former matches your markup.)
Docs:
Live Example:
$(".container").on("click", ".item", function() {
$(this).nextAll(".desc").first().html($(this).html());
});
.desc {
background-color: yellow;
min-height: 1em;
}
Click an item, and its text will be shown in the next .desc element after it (the ones with yellow backgrounds).
<hr>
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="desc"></div>
<div class="item">item 3</div>
<div class="item">item 4</div>
<div class="desc"></div>
<div class="item">item 5</div>
<div class="item">item 6</div>
<div class="desc"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>