javascriptjqueryslick.jswai-aria

How to change aria attribute with Jquery?


I have the following code where I would like to change the aria-describedby attribute to match the text in the <h3></h3> contained in that div. I need to identify each div by the .slick-slide class.

<div class="cards__card cards__card--1 cards__slide section--light slick-slide slick-current slick-active" data-slick-index="0" aria-hidden="false" tabindex="0" role="tabpanel" id="slick-slide00" aria-describedby="slick-slide-control00">
    <div class="cards__slide-wrapper self-center">
        <h3 class="section__header cards__header heading heading--h3 ">--- HEADER ---</h3>
        <div class="cards__item cards__item--copy">
            <p> ---  SAMPLE TEXT ---</p>
        </div>
        <div class="cards__pagination cards__pagination--black">
            <p class="copy--disclaimer">1 / 4</p>
        </div>
    </div>
</div>

I have tried the following to no avail:

$('div .slick-slide').each(function () {
    var h3 = $(this).closest("h3").text(); 
    $(this).attr("aria-describedby", h3);
});

Thank you in advance!


Solution

  • jQuery's .closest() searches up the hierarchy whereas you want to search within the .slick-slide container.

    Use .find() instead to search within an element.

    As mentioned by several comments, the aria-describedby is not a free text attribute. Its value should be a list of...

    the ids of the elements that describe the object.

    I would approach this by retrieving or creating the <h3> ID and assign that to the attribute.

    Also you might not definitely don't need jQuery

    document.querySelectorAll('.slick-slide[id]').forEach((c) => {
      const heading = c.querySelector('h3');
      if (heading) {
        if (!heading.id) {
          heading.id = `${c.id}--heading`;
        }
        c.setAttribute('aria-describedby', heading.id);
      }
      
      console.log('aria-describedby:', c.getAttribute('aria-describedby'));
    });
    <div
      class="cards__card cards__card--1 cards__slide section--light slick-slide slick-current slick-active"
      data-slick-index="0"
      aria-hidden="false"
      tabindex="0"
      role="tabpanel"
      id="slick-slide00"
      aria-describedby="slick-slide-control00"
    >
      <div class="cards__slide-wrapper self-center">
        <h3 class="section__header cards__header heading heading--h3">
          --- HEADER ---
        </h3>
        <div class="cards__item cards__item--copy">
          <p>--- SAMPLE TEXT ---</p>
        </div>
        <div class="cards__pagination cards__pagination--black">
          <p class="copy--disclaimer">1 / 4</p>
        </div>
      </div>
    </div>