javascript div要素内にノードが存在するかを判定する
- 作成日 2022.12.13
- javascript
- javascript
javascriptで、div要素内にノードが存在するかを判定するサンプルコードを記述してます。「childNodes」で子ノードを取得して何も存在しなければ「length」が「0」で返るので、これを利用します。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 108.0.5359.99
div要素内にノードが存在するかを判定
div要素内にノードが存在するかを判定するには、「childNodes.length」が「0」であるかにより判定することが可能です。
<div id="noelm"></div>
<div id="wrap"><p></p></div>
<script>
function hasElement(elm){
if (elm.childNodes.length === 0) return false;
return true;
}
console.log( hasElement(document.getElementById('noelm')) ); // false
console.log( hasElement(document.getElementById('wrap')) ); // ture
</script>
「改行」や「コメント」もノードの1つなので存在すると判定されます。
<div id="noelm">
</div>
<div id="wrap"><!-- comment --></div>
<script>
function hasElement(elm){
if (elm.childNodes.length === 0) return false;
return true;
}
console.log( hasElement(document.getElementById('noelm')) ); // ture
console.log( hasElement(document.getElementById('wrap')) ); // ture
</script>
「hasChildNodes」を使用しても結果は同じになります。
<div id="a"></div>
<div id="b"><p></p></div>
<div id="c">
</div>
<div id="d"><!-- comment --></div>
<script>
function hasElement(elm){
if (elm.childNodes.length === 0) return false;
return true;
}
console.log( document.getElementById('a').hasChildNodes() ); // false
console.log( document.getElementById('b').hasChildNodes() ); // ture
console.log( document.getElementById('c').hasChildNodes() ); // ture
console.log( document.getElementById('d').hasChildNodes() ); // ture
</script>
サンプルコード
以下は、
「判定」ボタンをクリックして、指定した「div」要素にノードが存在するかを判定するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
add.onclick = () => {
(sample.childNodes.length === 0) ? add.innerHTML = "true" : add.innerHTML = "false";
};
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<button id="add"
class="bg-gradient-to-r from-purple-400 to-blue-500 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
判定
</button>
</div>
</div>
</body>
</html>
判定されていることが確認できます。
-
前の記事
WinSCP ホームディレクトリに移動するショートカットキー 2022.12.12
-
次の記事
mongoDB コレクションの情報を一覧で取得する 2022.12.13
コメントを書く