javascriptで要素を削除する方法をご紹介していきます。
併せてjQueryでの書き方も記載しておきます。
ご紹介する要素の削除位置はこちら。
「idが"sample"のdiv」を基準としています。
<span>上の要素</span> // この要素を削除する方法 <div id="sample"> // この要素を削除する方法 test // この要素を削除する方法 </div> <span>下の要素</span> // この要素を削除する方法</pre>
削除位置の上から順に記載していきます。
上の兄弟要素削除
<span>上の要素</span> // この要素を削除する方法 <div id="sample"> test </div> <span>下の要素</span>
<script>
// remove()で要素を削除する方法(IE未対応)
var sampleDiv = document.getElementById('sample');
sampleDiv.previousSibling.remove();
// removeChild()で要素を削除する方法
var sampleDiv = document.getElementById('sample');
sampleDiv.parentNode.removeChild(sampleDiv.previousSibling);
// jQueryで要素を削除する方法
$('#sample').prev().remove();
</script>
ターゲット要素削除
<span>上の要素</span> <div id="sample"> // この要素を削除する方法 test </div> <span>下の要素</span>
<script>
// remove()で要素を削除する方法(IE未対応)
var sampleDiv = document.getElementById('sample');
sampleDiv.remove();
// removeChild()で要素を削除する方法
var sampleDiv = document.getElementById('sample');
sampleDiv.parentNode.removeChild(sampleDiv);
// jQueryで要素を削除する方法
$('#sample').remove();
</script>
要素内をすべて削除
<span>上の要素</span> <div id="sample"> test // この要素を削除する方法 </div> <span>下の要素</span>
<script>
// innerHTMLで要素を削除する方法
var sampleDiv = document.getElementById('sample');
sampleDiv.innerHTML = '';
// jQueryで要素を削除する方法
$('#sample').empty();
</script>
下の兄弟要素削除
<span>上の要素</span> <div id="sample"> test </div> <span>下の要素</span> // この要素を削除する方法
<script>
// remove()で要素を削除する方法(IE未対応)
var sampleDiv = document.getElementById('sample');
sampleDiv.nextSibling.remove();
// removeChild()で要素を削除する方法
var sampleDiv = document.getElementById('sample');
sampleDiv.parentNode.removeChild(sampleDiv.nextSibling);
// jQueryで要素を削除する方法
$('#sample').next().remove();
</script>
