編輯:document.querySelectorAll 解決方案有效,并且更易于閱讀和理解。我自己的解決方案(在下面的答案中)也有效,而且速度稍快。
我需要找到具有特定類的任何元素的子元素,例如,
<li class="myclass"><a>This is the link I need to find</a></li>
這樣我就可以設定和洗掉錨點的一些屬性。
我可以使用 getElementsByClassName 輕松找到所有串列項,但 getElementsByTagName 失敗,因為它僅適用于單個宣告的元素(不適用于集合)。因此,這不起作用:
const noLinks = document.getElementsByClassName('myclass');
for (let noLink of noLinks) {
const matches = noLinks.getElementsByTagName('a');
matches.setAttribute('role', 'link');
matches.setAttribute('aria-disabled', 'true');
matches.removeAttribute('href');
matches.removeAttribute('rel');
};
如何遍歷回傳的元素并獲取其中的標簽?
uj5u.com熱心網友回復:
OP 的代碼可以切換到更具表現力的代碼(基于 eg querySelectorAll),例如...
document
.querySelectorAll('.myclass a')
.forEach(elmNode => {
elmNode.setAttribute('role', 'link');
elmNode.setAttribute('aria-disabled', 'true');
elmNode.removeAttribute('href');
elmNode.removeAttribute('rel');
});
uj5u.com熱心網友回復:
問題是getElementsByTagName回傳一個活的 HTMLCollection 元素,你的matches變數包含一個陣列,而必須是一個元素才能應用到他的某些屬性href, rel...,所以他需要是一個元素而不是 elment s,要解決這個問題,只需訪問第一個元素不是全部,或者使用querySelectorwhich 回傳第一個匹配的元素(如果存在)。
const noLinks = document.getElementsByClassName('myclass');
for (let noLink of noLinks) {
//v-- access to noLink not noLinks
const matches = noLink.getElementsByTagName('a')[0]; //<-- or noLinks.querySelector('a')
matches.setAttribute('role', 'link');
matches.setAttribute('aria-disabled', 'true');
matches.removeAttribute('href');
matches.removeAttribute('rel');
};
uj5u.com熱心網友回復:
以下解決方案有效。我可能會測驗其他 2 個提供的解決方案并在它們有效時給它們投票,但我發布此答案以便其他人可以看到解決此問題的不同方法。
// Modify the attributes on the <a> inside the <li> with class "nolink".
const noLinks = document.getElementsByClassName('nolink');
Array.prototype.forEach.call(noLinks, function(noLink) {
const matches = noLink.getElementsByTagName('a')[0];
matches.setAttribute('role', 'link');
matches.setAttribute('aria-disabled', 'true');
matches.removeAttribute('href');
matches.removeAttribute('rel');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358984.html
