JavaScript入門講座

Home > DOMによる属性の取得

DOMによる属性の取得

DOMにより要素ノードの属性の値を取得する場合、getAttribute()メソッドを使用します。

getAttribute()メソッド

要素ノード.getAttribute(属性名)

以下のサンプルではgetAttribute()メソッドによりイメージファイルのファイル名を表示しています。

<html>
<head>
<title>JavaScript</title>
<script type="text/javascript">
function getAttributes(){
    var img1 = document.getElementById("img1");
    alert(img1.getAttribute("src"));
}
</script>
<body>
<img id="img1" src="imgFile1.jpg" name="file1" alt="イメージファイル1"
 width="50px" height="50px" lowsrc="imglowFile1.jpg"
 border="2" hspace="10" vspace="15">
<form name="fm">
<input type="button" value="確認" onclick="getAttributes()">
</form>
</body>
</html>