184
187

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-02-04

要素の追加方法がいろいろあるのでメモ。
<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>
184
187
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
184
187

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?