この記事は...
- pタグ、divタグで書かれた文字列に新しく文字列を追加するコード
- prepend appendのjQuery、after beforeのJavaScript両方のコードを掲載
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<div id="id-text" class="text">
<p>月曜日</p>
<p>火曜日</p>
<p>水曜日</p>
<p>木曜日</p>
<p>金曜日</p>
<p>土曜日</p>
</div>
<script src="src/index.js"></script>
</body>
</html>
pタグで書かれた6つの要素の文頭(赤枠)と末尾(青枠)に新しく文字列を追加します
文頭に追加
.prepend 〜jQuery〜
.prepend()
$('要素').prepend('追加したい任意の文字列')$(() => {
$(".text").prepend("<p>日曜日</p>");
});
文頭(赤枠)に追加されました
.before 〜JavasScript〜
const pTop = document.getElementById('id-text')
//divのid-textを取得しpTopに代入//
const newP = document.createElement('p')
//新しい要素newpを作成//
newP.textContent = '日曜日'
//newPにテキストを追加//
pTop.before(newP)
//.beforメソッドを使用しpTop(指定した要素の前)にnewPを追加//上記の書き方以外にもあると思うんですが、やっぱりjQueryの方が短く書けていいですよね(・∀・)
末尾に追加
.append 〜jQuery〜
.append
$('要素').append('追加したい任意の文字列')$(() => {
$(".text").append("<p>日曜日</p>");
});
今度は末尾(青枠)に追加されました
.after 〜JavasScript〜
const pTop = document.getElementById("id-text");
const newP = document.createElement("p");
newP.textContent = "日曜日";
pTop.after(newP);詳細は端折りますが.beforeと考え方は一緒です


