jQuery - HTML の設定・取得・削除
公開日:2018-12-10 更新日:2019-05-14
[jQuery]
1. 概要
指定した要素の HTML の設定と取得と削除を行います。
要素の HTML の設定
要素の HTML の取得
要素の HTML の削除
要素の HTML の設定
$(セレクタ).html( HTMLの文字列 );
$(セレクタ).html( jQueryオブジェクト );
要素の HTML の取得
var html = $(セレクタ).html();
要素の HTML の削除
$(セレクタ).html('');
2. サンプル
<div>タグの内容を動的に書き換えます。
最初の3行が最初の要素で、最後の行が書き換え後のHTMLです。
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>jQuery</title><style>body{color:#fff; background-color:#000;}</style></head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- 画面 -->
<div id="fruits">
<div>apple</div>
<div>orange</div>
<div>banana</div>
</div>
<!-- Script -->
<script>
$(function(){
//取得
console.log( $("#fruits").html() );
//設定
$("#fruits").html('<div>strawberry</div><div>grape</div><div>melon</div>');
//取得
console.log( $("#fruits").html() );
});
</script>
</body></html>
最初の3行が最初の要素で、最後の行が書き換え後のHTMLです。
<div>apple</div>
<div>orange</div>
<div>banana</div>
<div>strawberry</div><div>grape</div><div>melon</div>
実行結果:画面