リンク付きの画像をcreateElementして、appendChildするまでの一連のJavaScript処理を教えてください。ちなみにリンクタグにはclass名を任意につけたいです。
jQueryやprototypeは使いません。
これでどうでしょうか。
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>
これでどうでしょうか。
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>
ありがとうございます。
ほぼ完璧に近いご回答でした!
var img1 = document.createElement("img");
img1.setAttribute("img","xxx.img");
img1.setAttribute("class","xxx");
document.body.appendChild(img1);
もしくは
document.getElementById("div1").appendChild("img1");
みたいに
ありがとうございます。
厳密には、imgタグ(オブジェクト)へのクラス名付けなので、1番目の回答者の方が、やはり完璧です。
(例題の丁寧さも含めて)
ありがとうございます。
ほぼ完璧に近いご回答でした!