JavaScript >> Javascript 文檔 >  >> JavaScript

如何使用 JavaScript 獲取屬性的值

要獲取元素屬性的值,可以使用 getAttribute() 方法。此方法返回具有指定名稱的屬性的值。如果屬性不存在,則返回null 或一個空字符串 ("" )。

假設您有以下錨元素:

<a href="http://example.com" title="Go Back" data-role="self">Click Me</a>

現在您要獲取 href 的值 屬性。這是您可以使用的代碼片段:

const anchor = document.querySelector('a');

const href = anchor.getAttribute('href');

console.log(href); // http://example.com

getAttribute() 方法也適用於 HTML5 data-* 屬性。

例如,要獲取 data-role 的值 錨元素的屬性,可以使用 getAttribute() 方法如下:

const anchor = document.querySelector('a');

const role = anchor.getAttribute('data-role');

console.log(role); // self

如果您想將屬性的值作為 Attr 對象,使用 getAttributeNode() 替代方法:

const anchor = document.querySelector('a');

const attr = anchor.getAttributeNode('title');

console.log(attr.value); // Go Back

getAttribute() 該方法適用於所有現代瀏覽器,以及 IE9 及更高版本。


Tutorial JavaScript 教程
  1. Next.js - 數據故事

  2. 2020 年你不應該使用 Protractor 的 5 個理由

  3. 使用快速刷新啟動 React Native Web 項目的一個命令 👏 👌

  4. 我是如何製作一個簡單的交互式圓形圖表 - 1

  5. 為什麼使用 for...in 進行數組迭代是個壞主意?

  6. 在 EventEmitter 上,我如何知道我可以收聽的所有事件?

  7. Vue 單文件組件

  1. 解決方案:俄羅斯娃娃信封

  2. 使用投票與您的團隊達成風格指南共識

  3. 使用 Spotify API 的 Next.js 完整初學者教程

  4. 開發日誌 6/8/2020:避免拉兔子洞

  5. Node.js 中的安全隨機令牌

  6. 如何計算活動的javascript超時?

  7. 在 Postman 中使用變量和鏈接請求

  1. React v18:useTransition 鉤子——為什麼???

  2. 使用 docker-compose 的 Nodejs Nginx 負載均衡器

  3. 使用 Node.js 構建 JavaScript 命令行界面 (CLI)

  4. 在 React App 中使用 Firebase 進行身份驗證。 🤺🔥