Reputation: 98
HTML
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 1</h3>
</div>
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 2</h3>
</div>
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 3</h3>
</div>
jQuery
$('a:not([aria-label])').attr('aria-label', function() {
var txt = $(".box-container > .box-title").text();
$(this).attr("aria-label", txt);
});
The problem is that the above div appears 3 times inside the whole page, so the code above will return and apply as an aria-label in the link, all the titles that have these classes. Example: aria-label="Title element 1Title element 2Title element3"
So I am trying to figure out why the above does not apply to the link of the div, the specific .box-title class for each div, only.
What I try to achieve and $(this) does not work properly:
<div class="box-container">
<a href="#" aria-label="Title 1"></a>
<h3 class="box-title">Title 1</h3>
</div>
<div class="box-container">
<a href="#" aria-label="Title 2"></a>
<h3 class="box-title">Title 2</h3>
</div>
<div class="box-container">
<a href="#" aria-label="Title 3"></a>
<h3 class="box-title">Title 3</h3>
</div>
Upvotes: 0
Views: 242
Reputation: 11
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 1</h3>
</div>
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 2</h3>
</div>
<div class="box-container">
<a href="#"></a>
<h3 class="box-title">Title 3</h3>
</div>
<script>
$('a:not([aria-label])').attr('aria-label', function() {
var txt = $(this).parent().find(".box-title").text();
$(this).attr("aria-label", txt);
});
</script>
Upvotes: 1