In my HTML code, I have a group of spans within a div that I am attempting to match and relocate to a corresponding id. Each span contains a data attribute that corresponds to the parent ID of the target element. My goal is to utilize jQuery to find the matching data attributes in the spans and then insert them before a separate span within the parent div IDs.
Here is an excerpt from my code:
HTML
<div id="id-expand-2">
<a class="thing" href="#">
<div class="item-title">
<span>Title 1</span>
</div>
</a>
</div>
<div id="id-expand-4">
<a class="thing" href="#">
<div class="item-title">
<span>Title 2</span>
</div>
</a>
</div>
<div id="id-expand-6">
<a class="thing" href="#">
<div class="item-title">
<span>Title 3</span>
</div>
</a>
</div>
<div class="vid-imgs">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
</div>
Essentially, I want each span within the vid-imgs
class with the data-item
attribute to align with the ID of its parent div and be inserted using .append()
right after the item-title
class.
The expected outcome would resemble:
<div id="id-expand-2">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 1</span>
</div>
</a>
</div>
<div id="id-expand-4">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 2</span>
</div>
</a>
</div>
<div id="id-expand-6">
<a class="thing" href="#">
<div class="item-title">
<span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
<span>Title 3</span>
</div>
</a>
</div>
I am uncertain about how to properly match each element altogether.
I was contemplating utilizing an each function like this:
$(".vid-imgs").each(function () {
var items = $(".item").attr("data-item");
console.log(items);
});
However, it appears to only retrieve the first item within the vid-imgs
div. After staring at this for hours, I think my eyes need a break!