I to need extract text from tags, which are under every image I have on my website. My goal is to make a link with same URL as images has. This is not issue, this already working. Problem is that I need the value of the data-group
attribute from the span tag inside this link, for every picture inside grid, so in case I have two pictures next to each other, they will have same data-group name from common span tag.
$(document).ready(function() {
$('.two_pics div img').each(function() {
var $img = $(this);
<!-- var test = $(this).parent().parent().children(':first').children().children(); -->
<!-- var one = two.getElementsByTagName("span")[0]; -->
<!-- var a = document.getElementsByClassName("two_pics"); -->
<!-- a.getElementsByTagName("span"); -->
var list = document.getElementsByClassName("two_pics")[0];
var test = document.getElementsByTagName("span")[0];
console.log(test.innerText);
<!-- console.log($one.textContent); -->
$img.wrap('<a href="' $img.attr('src') '" class="lightbox" data-group="' test.innerText '"></a>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="div_grid" id="myUL">
<div style="order:1" class="two_pics">
<div><a><span>KZO3</span></a></div>
<div><img src="sucast_kroja/315.jpg"></div>
<div><img src="sucast_kroja/316.jpg"></div>
</div>
<div style="order:2" class="two_pics">
<div><a><span>KZO4</a></div>
<div><img src="sucast_kroja/398.png" data-group="398"></div>
<div><img src="sucast_kroja/397.png" data-group="398"></div>
</div>
CodePudding user response:
Try this simpler script using closest to get the text
$(document).ready(function() {
$('.two_pics div img').each(function() {
const $img = $(this);
const text = $img.closest(".two_pics").find("div span").text()
$img.wrap(`<a href="${$img.attr('src')}" class="lightbox" data-group="${text}"></a>`);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="div_grid" id="myUL">
<div style="order:1" class="two_pics">
<div><a><span>KZO3</span></a></div>
<div><img src="sucast_kroja/315.jpg"></div>
<div><img src="sucast_kroja/316.jpg"></div>
</div>
<div style="order:2" class="two_pics">
<div><a><span>KZO4</a></div>
<div><img src="sucast_kroja/398.png" data-group="398"></div>
<div><img src="sucast_kroja/397.png" data-group="398"></div>
</div>