DOM操作の質問です。

リンク付きの画像をcreateElementして、appendChildするまでの一連のJavaScript処理を教えてください。ちなみにリンクタグにはclass名を任意につけたいです。
jQueryやprototypeは使いません。

回答の条件
  • URL必須
  • 1人2回まで
  • 登録:
  • 終了:2008/11/09 19:27:44
※ 有料アンケート・ポイント付き質問機能は2023年2月28日に終了しました。

ベストアンサー

id:worldtravel No.1

回答回数34ベストアンサー獲得回数4

ポイント50pt

これでどうでしょうか。

IEとそれ以外でclassの指定方法が異なるのでご注意ください。

http://q.hatena.ne.jp/1226147589

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript"><!--
window.onload = function(){
	var el_i = document.createElement("img");
	el_i.setAttribute("src", "http://q.hatena.ne.jp/images/logo_hatena.gif");
	var el_a = document.createElement("a");
	el_a.setAttribute("href", "http://q.hatena.ne.jp/");
	el_a.setAttribute("className", "hoge"); // IE
//	el_a.setAttribute("class", "hoge");     // 他
	el_a.setAttribute("target", "_blank");
	el_a.appendChild(el_i);
	document.getElementById("hoge").appendChild(el_a);
};
--></script>
</head>

<body>
<div id="hoge"></div>
</body>
</html>
id:P-mako

ありがとうございます。

ほぼ完璧に近いご回答でした!

2008/11/09 19:25:36

その他の回答1件)

id:worldtravel No.1

回答回数34ベストアンサー獲得回数4ここでベストアンサー

ポイント50pt

これでどうでしょうか。

IEとそれ以外でclassの指定方法が異なるのでご注意ください。

http://q.hatena.ne.jp/1226147589

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript"><!--
window.onload = function(){
	var el_i = document.createElement("img");
	el_i.setAttribute("src", "http://q.hatena.ne.jp/images/logo_hatena.gif");
	var el_a = document.createElement("a");
	el_a.setAttribute("href", "http://q.hatena.ne.jp/");
	el_a.setAttribute("className", "hoge"); // IE
//	el_a.setAttribute("class", "hoge");     // 他
	el_a.setAttribute("target", "_blank");
	el_a.appendChild(el_i);
	document.getElementById("hoge").appendChild(el_a);
};
--></script>
</head>

<body>
<div id="hoge"></div>
</body>
</html>
id:P-mako

ありがとうございます。

ほぼ完璧に近いご回答でした!

2008/11/09 19:25:36
id:atmarkbienna No.2

回答回数61ベストアンサー獲得回数3

ポイント20pt

var img1 = document.createElement("img");

img1.setAttribute("img","xxx.img");

img1.setAttribute("class","xxx");

document.body.appendChild(img1);

もしくは

document.getElementById("div1").appendChild("img1");

みたいに

http://www.www.www

id:P-mako

ありがとうございます。

厳密には、imgタグ(オブジェクト)へのクラス名付けなので、1番目の回答者の方が、やはり完璧です。

(例題の丁寧さも含めて)

2008/11/09 19:27:15

コメントはまだありません

この質問への反応(ブックマークコメント)

「あの人に答えてほしい」「この質問はあの人が答えられそう」というときに、回答リクエストを送ってみてましょう。

これ以上回答リクエストを送信することはできません。制限について

回答リクエストを送信したユーザーはいません