まずはアンカーを作成して挿入してみます。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <div></div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript"> // アンカーを作成して挿入 $('<p><a>jQuery</a></p>').appendTo('body'); </script> </body> </html>
これで「jQuery」というアンカーが表示されるようになりました。
次にアンカーにhref属性を設定してみます。
script要素以外は同じなので省略します。
<script type="text/javascript"> $('<p><a>jQuery</a></p>') // pタグの子要素であるaタグを選択し、href属性を設定 .find('a').attr('href', 'http://www.jquery.com/') // 選択を解除 .end() .appendTo('body'); </script>
「.end()」がポイントです。
10/30 html形式のコメントを「//」のコメントに修正