jQueryで要素のテキストやHTMLを変更するtext()とhtml()の使い方
jQueryでテキスト文字列やHTMLタグの取得・変更・削除を行うメソッド.text()と.html()についてまとめました。
指定した要素のテキストを取得する
要素のテキストの内容は、$(要素).text()、$(要素).html()で取得できます。
サンプルコード
<div class="sample1">取得用のテキスト</div>
<script>
$(function(){
var text = $('.sample1').text();
console.log(text);
var html = $('.sample1').html();
console.log(html);
});
</script>
取得用のテキスト
text()とhtml()の違い
text()で取得するテキストにはHTMLタグは含まれません。
HTMLタグを含めて取得したい場合は$(要素).html()のメソッドを使用する必要があります。
- .text()はテキストの取得・変更
- .html()はHTMLの取得・変更
サンプルコード
<div class="sample2">
<p>取得用のテキスト</p>
</div>
<script>
$(function(){
//text()で取得
var text = $('.sample2').text();
console.log(text);
//html()で取得
var html = $('.sample2').html();
console.log(html);
});
</script>
取得用のテキスト
指定した要素が複数あった場合は連結されて取得する
指定した要素が複数存在した場合は1つのテキストとして連結されて取得します。
サンプルコード
<ul class="ul_sample1">
<li>リスト1</li>
<li>リスト2</li>
<li>リスト3</li>
</ul>
<script>
$(function(){
//text()で取得
var text = $('.ul_sample1').text();
console.log(text);
//html()で取得
var html = $('.ul_sample1').html();
console.log(html);
});
</script>
- リスト1
- リスト2
- リスト3
個別にそれぞれ取得し処理したい場合は、each()などの繰り返しメソッドを活用できます。
サンプルコード
<ul class="ul_sample2">
<li>リスト1</li>
<li>リスト2</li>
<li>リスト3</li>
</ul>
<script>
$(function(){
$('.ul_sample2 li').each(function(key, value){
console.log( $(value).text() );
});
});
</script>
- リスト1
- リスト2
- リスト3
フォーム内のテキストの取得はval()メソッドを使用する
.text()ではフォーム内のテキストの取得はできません。
フォームの値はval()で取得・変更ができます。
サンプルコード
<input type="text" class="textbox" value="テキスト">
<input type="button" class="textbox_check" value="テキストボックスの値を取得">
<script>
$(function(){
$('.textbox_check').click(function(){
alert( $('.textbox').val() );
});
});
</script>
フォーム操作について詳しくはこちらのページをご確認ください。
指定した要素のテキストを変更する
セレクタで指定した要素の中身を変更したい場合は、.text()や.html()の中に直接値を入力します。
テキストのみ変更したい場合は.text()を、HTMLタグを反映させたい場合は.html()を使用しましょう。
サンプルコード
<div class="sample3_1">このテキスト1を変更する</div>
<div class="sample3_2">このテキスト2を変更する</div>
<input type="button" class="sample_btn3_1" value="text()でテキスト1を変更する">
<input type="button" class="sample_btn3_2" value="text()でテキスト2を変更する">
<input type="button" class="sample_btn3_3" value="html()でテキスト2を変更する">
<script>
$(function(){
$('.sample_btn3_1').click(function(){
$('.sample3_1').text('変更しました!');
});
//pタグ付きのテキストをtext()で挿入(タグは反映されない)
$('.sample_btn3_2').click(function(){
$('.sample3_2').text('<p>変更しました!</p>');
});
//pタグ付きのテキストをhtml()で挿入(タグは反映される)
$('.sample_btn3_3').click(function(){
$('.sample3_2').html('<p>変更しました!</p>');
});
});
</script>
このテキスト1を変更する
このテキスト2を変更する
覚えてみればこの2つのメソッドは共通点が多く、難なく違いを覚えられると思います。
頻繁に使うメソッドなので是非身につけてください。
以上、jQueryで要素のテキストやHTMLを変更するtext()とhtml()の使い方、でした。

ディスカッション
コメント一覧
まだ、コメントがありません