184
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

HTML要素の追加方法いろいろ 挿入位置で分類

要素の追加方法がいろいろあるのでメモ。
<div id="test">test</div>に対してどこに挿入するかで分けました。

開始タグの前に挿入

insertAdjacentHTML ("beforebegin")

var test = document.getElementById('test');

test.insertAdjacentHTML('beforebegin','<div>BeforeBegin</div>');

insertBefore

var element = document.createElement('div');
element.innerHTML = "BeforeBegin";

document.body.insertBefore(element, test);

jQueryのbefore または insertBefore

$('#test').before('<div>BeforeBegin</div>');
//または
$('<div>BeforeBegin</div>').insertBefore('#test');

結果

<div>BeforeBegin</div>
<div id="test">
 test
</div>

開始タグの後に挿入

insertAdjacentHTML ("afterbegin")

test.insertAdjacentHTML('afterbegin','<div>AfterBegin</div>');

jQueryのprepend または prependTo

$('#test').prepend('<div>AfterBegin</div>');
// または
$('<div>AfterBegin</div>').prependTo('#test');

 結果

<div id="test">
 <div>AfterBegin</div>
 test
</div>

終了タグの前に挿入

insertAdjacentHTML ("beforeend")

test.insertAdjacentHTML('beforeend', '<div>BeforeEnd</div>');

jQueryのappend または appendTo

$('#test').append('<div>BeforeEnd</div>');
// または
$('<div>BeforeEnd</div>').appendTo('#test');

結果

<div id="test">
 test
 <div>BeforeEnd</div>
</div>

終了タグの後に挿入

insertAdjacentHTML ("afterend")

test.insertAdjacentHTML('afterend','<div>AfterEnd</div>');

jQueryのafterまたはinsertAfter

$('#test').after('<div>AfterEnd</div>');
//または
$('<div>AfterEnd</div>').insertAfter('#test');

結果

<div id="test">
  test
</div>
<div>AfterEnd</div>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
184
Help us understand the problem. What are the problem?