簡體   English   中英

從innerHTML獲取href

[英]Get the href from innerHTML

我正在嘗試在 React 中編寫一個單元測試來檢查鏈接中的href值。 我有以下代碼行:

var result = document.getElementsByClassName("MuiTypography-root")[0].innerHTML;

這將正確返回 HTML 代碼片段:

<a class="MuiTypography-root MuiLink-root MuiLink-underlineHover MuiTypography-colorPrimary" href="www.test.com" target="_blank" rel="noreferrer">1234 - Example</a>

但我只追求 href 值: www.test.com

我怎樣才能得到這個值? 如果我嘗試console.log(result.href)我得到undefined

使用.getAttribute()方法。

例如: result.getAttribute('href')

嘗試這個:

var href = document.getElementsByClassName("MuiTypography-root")[0].getAttribute("href");

這是示例:

 var href = document.getElementsByClassName("MuiTypography-root")[0].getAttribute("href"); console.log(href);
 <a class="MuiTypography-root MuiLink-root MuiLink-underlineHover MuiTypography-colorPrimary" href="www.test.com" target="_blank" rel="noreferrer">1234 - Example</a>

你試過attributes嗎? https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes

您不是在這里尋找內部 HTML,而是嘗試找到返回元素“屬性”的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM