關閉。這個問題需要細節或清晰。它目前不接受答案。
想改進這個問題?通過編輯此帖子添加詳細資訊并澄清問題。
4天前關閉。
改進這個問題如何在內部按名稱捕獲元素屬性。
如何獲取文本“查看 test2”的 href https://www.test2.com
輸入是“查看 test2”,它位于 div 標簽內 如何使用 javascript 獲取輸出“https://www.test2.com”結果
<div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test.com">
<span dir="ltr">
<span class="visually-hidden">View test</span>
</span>
</a>
</span>
</div>
</div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test2.com">
<span dir="ltr">
<span class="visually-hidden">View test2 </span>
</span>
</a>
</span>
</div>
</div>
</div>
uj5u.com熱心網友回復:
- 獲取所有包含文本的 span。
- 回圈它們。
- 找到一個匹配的
- 閱讀文本。
- 比較一下。
- 找到鏈接。
- 選擇屬性。
function findHref(text) {
// find the elements that have the text you are looking for
const hiddenSpans = document.querySelectorAll(".visually-hidden");
// find the element with the text you are looking for
const matchedElem = Array.from(hiddenSpans).find(
elem => elem.textContent.trim() === text
);
if (!matchedElem) {
console.error('not found');
return null;
}
// find the anchor
const anchor = matchedElem.closest('a');
// return the attribute
return anchor?.href;
}
console.log(findHref('View test2'));
console.log(findHref('View test'));
<div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test.com">
<span dir="ltr"> <span class="visually-hidden">
<!---->View test <!----></span></span>
</a>
</span>
</div>
</div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test2.com">
<span dir="ltr"> <span class="visually-hidden">
<!---->View test2 <!----></span></span>
</a>
</span>
</div>
</div>
</div>
uj5u.com熱心網友回復:
像這樣
此代碼可以添加一些測驗
const href = [...document.querySelectorAll('.visually-hidden')]
.find(span => span.innerText.trim() === 'View test2')
.closest('a').href;
console.log(href)
<div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test.com">
<span dir="ltr">
<span class="visually-hidden">View test</span>
</span>
</a>
</span>
</div>
</div>
<div>
<div>
<span class="entity-result__title-text t-16">
<a class="test-link" href="https://www.test2.com">
<span dir="ltr">
<span class="visually-hidden">View test2 </span>
</span>
</a>
</span>
</div>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/407923.html
標籤:
