How to get value from inside <li> element and put it in image attribute tag using jQuery
I want to get a value from an H3 element and put it in an image attribute such as title and alt. see my code below.
$('ul.products').each(function() {
$(this).find('li h3').each(function() {
var current = $(this);
if (current.children().size() > 0) {
return true;
}
console.log($(this).text());
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="products">
<li>
<a href="#">
<img src="/path/" title="(Get value from h3)" alt="(Get value from h3)">
</a>
<h3>Mytitle1</h3>
</li>
<li>
<a href="#">
<img src="/path/" title="(Get value from h3)" alt="(Get value from h3)">
</a>
<h3>Mytitle2</h3>
</li>
<li>
<a href="#">
<img src="/path/" title="(Get value from h3)" alt="(Get value from h3)">
</a>
<h3>Mytitle3</h3>
</li>
</ul>+4
4 answers
$(function() {
$('.products li').each(function() {
var item = $(this);
var text = item.find('h3').text();
item.find('img').attr({
'title': text,
'alt': text
});
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="products">
<li>
<a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a>
<h3>Mytitle1</h3>
</li>
<li>
<a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a>
<h3>Mytitle2</h3>
</li>
<li>
<a href="#"><img src="/path/" title="(Get value from h3)" alt="(Get value from h3)"> </a>
<h3>Mytitle3</h3>
</li>
</ul>0