diff --git a/js/src/tooltip.js b/js/src/tooltip.js index 797afb134fd3c600a234029c3f6414140899be24..62b33883988c5c0282fbc35a09450ae3e735fe11 100644 --- a/js/src/tooltip.js +++ b/js/src/tooltip.js @@ -584,6 +584,10 @@ class Tooltip extends BaseComponent { if (title || originalTitleType !== 'string') { this._element.setAttribute('data-bs-original-title', title || '') + if (title && !this._element.getAttribute('aria-label') && !this._element.textContent) { + this._element.setAttribute('aria-label', title) + } + this._element.setAttribute('title', '') } } diff --git a/js/tests/unit/tooltip.spec.js b/js/tests/unit/tooltip.spec.js index e8572b30017c8941a8f47f99f1fb02c9ed3d91c3..b119807511b87a00bab2952d529739327e3410c0 100644 --- a/js/tests/unit/tooltip.spec.js +++ b/js/tests/unit/tooltip.spec.js @@ -1050,6 +1050,59 @@ describe('Tooltip', () => { }) }) + describe('aria-label', () => { + it('should add the aria-label attribute for referencing original title', done => { + fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Another tooltip"></a>' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).toBeDefined() + expect(tooltipEl.getAttribute('aria-label')).toEqual('Another tooltip') + done() + }) + + tooltip.show() + }) + + it('should not add the aria-label attribute if the attribute already exists', done => { + fixtureEl.innerHTML = '<a href="#" rel="tooltip" aria-label="Different label" title="Another tooltip"></a>' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).toBeDefined() + expect(tooltipEl.getAttribute('aria-label')).toEqual('Different label') + done() + }) + + tooltip.show() + }) + + it('should not add the aria-label attribute if the element has text content', done => { + fixtureEl.innerHTML = '<a href="#" rel="tooltip" title="Another tooltip">text content</a>' + + const tooltipEl = fixtureEl.querySelector('a') + const tooltip = new Tooltip(tooltipEl) + + tooltipEl.addEventListener('shown.bs.tooltip', () => { + const tooltipShown = document.querySelector('.tooltip') + + expect(tooltipShown).toBeDefined() + expect(tooltipEl.getAttribute('aria-label')).toBeNull() + done() + }) + + tooltip.show() + }) + }) + describe('jQueryInterface', () => { it('should create a tooltip', () => { fixtureEl.innerHTML = '<div></div>'