Created
February 1, 2020 11:00
-
-
Save tsmd/2daced5d3b9ef6307eaf0c3cc7497b5a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 引数を起点に兄弟要素、親の兄弟要素、さらに親の兄弟要素、…を取得する | |
* @param {Element} baseElement | |
* @return {[Element]} 対象となるHTML要素 | |
*/ | |
export function collectAllSiblings(baseElement) { | |
const targets = [] | |
let current = baseElement | |
while (current && current !== document.body) { | |
const siblings = Array.from(current.parentNode.children) | |
siblings.forEach(el => { | |
if (el !== current) { | |
targets.push(el) | |
} | |
}) | |
current = current.parentNode | |
} | |
return targets | |
} | |
/** | |
* 引数を起点に兄弟要素、親の兄弟要素、さらに親の兄弟要素、…を aria-hidden="true" にする | |
* @param {Element} baseElement | |
* @return {[Element]} 対象となるHTML要素 | |
*/ | |
export function setAriaHiddenAllSiblings(baseElement) { | |
this.collectAllSiblings(baseElement).forEach(el => { | |
// 現在の aria-hidden の値を退避する | |
el.dataset.storedAriaHidden = JSON.stringify(el.getAttribute('aria-hidden')) | |
el.setAttribute('aria-hidden', 'true') | |
}) | |
} | |
/** | |
* 引数を起点に兄弟要素、親の兄弟要素、さらに親の兄弟要素、…を aria-hidden="false" にする | |
* @param {Element} baseElement | |
* @return {[Element]} 対象となるHTML要素 | |
*/ | |
export function removeAriaHiddenAllSiblings(baseElement) { | |
this.collectAllSiblings(baseElement).forEach(el => { | |
const stored = JSON.parse(el.dataset.storedAriaHidden || 'null') | |
delete el.dataset.storedAriaHidden | |
if (stored === null) { | |
el.removeAttribute('aria-hidden') | |
} else { | |
el.setAttribute('aria-hidden', stored) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment