初心者向けjQuery入門

初心者向けjQuery入門講座です

未分類

jQuery beforeとafterの違いと要素の追加

投稿日:2017年8月12日 更新日:

jQuery beforeとafterの違いと要素の追加

jQuery beforeとafterの違い

beforeとafterは基本的な動作は似てます。
共通してるのは要素を追加することです。
違うのは挿入場所だけですね。

あれ、同じこと昨日の記事で書いたような気がします。

jQuery prependとappendの違いと要素の追加

prependとappendとタグを使用して要素を追加するだけなら同じ動作します。

じゃあいらないじゃん。

細かい動作は違うんです。

具体的には文字列を指定した場合が動作が違います。

jQuery before 前に要素の追加

before は英語で前にという意味です。

サンプル
$(“セレクタ”).before(“タグや文字列”)

サンプル

<html>
<head>
<script src=”jquery-3.2.1.js”></script>

<script>
$(document).ready(function(){

$(“.red”).before(“<h3>pink</h3>”)

 

});
</script>
<title>

</title>
</head>
<body>
<div>
<h3 class=”red”>red</h3>
<h3>Green</h3>
<h3>yellow</h3>
<h3>Blue</h3>
</div>

</body>
</html>

実行結果は

pink

red

Green

yellow

Blue

ちゃんとredの前に挿入されましたね。

問題は文字列ですね。

サンプル

<html>
<head>
<script src=”jquery-3.2.1.js”></script>

<script>
$(document).ready(function(){

$(“.red”).before(“pink”)

 

});
</script>
<title>

</title>
</head>
<body>
<div>
<h3 class=”red”>red</h3>
<h3>Green</h3>
<h3>yellow</h3>
<h3>Blue</h3>
</div>

</body>
</html>

実行結果は

pink

red

Green

yellow

Blue

になります。

見た目は文字にすると同じですが

タグで指定していないので何もタグのない文字列が表示されています。

prependと文字列を指定した時に動作が違うといいました。

prependの場合は文字列だと指定したタグの先頭に文字列が追加されます。

pinkredみたいな感じです。

jQuery after 後に要素の追加

before は英語で後にという意味です。

サンプル
$(“セレクタ”).after(“タグや文字列”)

 

サンプル

<html>
<head>
<script src=”jquery-3.2.1.js”></script>

<script>
$(document).ready(function(){

$(“.red”).after(“<h3>pink</h3>”)

 

});
</script>
<title>

</title>
</head>
<body>
<div>
<h3 class=”red”>red</h3>
<h3>Green</h3>
<h3>yellow</h3>
<h3>Blue</h3>
</div>

</body>
</html>

実行結果は

red

pink

Green

yellow

Blue

です。

文字列の場合も見た目は同じです。

pinkだけタグのない文字列になってしまいます。

 

 

 

 

スポンサードリンク




スポンサードリンク




-未分類
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

jQuery 子孫セレクタとユニバーサルセレクタと複数

jQuery 子孫セレクタとユニバーサルセレクタと複数 jQuery 子孫セレクタ 子孫セレクタとは 要素には親要素と子要素があります。 ulだと子はliですね。 それとdivの中にp要素を入れ子にし …

no image

jQuery textメソッドとhtmlの違い 文字列を変更する

jQuery textメソッド 文字列を変更する jQuery textメソッド 文字列を変更する textメソッドは要素のtextを変更することができます。 $(“セレクタ” …

no image

jQuery fadeInとfadeOutフェードインとフェードアウトする方法

jQuery fadeInとfadeOutフェードインとフェードアウトする方法 jQuery fadeInフェードインする方法 フェードインの英語の意味は次第に明るくなる、次第にはっきりするです。 f …

no image

jQuery addclassクラスを追加する方法

jQuery addclassクラスを追加する方法 jQuery addclassクラスを追加する方法 addclassクラスは要素にクラスを設定できます。 どういうことかというこクラスのタブにhtm …

no image

jQuery slideUpとslideDownとslideToggle

jQuery slideUpとslideDownとslideToggle jQuery slideUp slideUpはスライドをアップします。 要素が上に上がっていき非表示になります。 サンプル $ …