Risposte:
Un paio di modi:
if (element.firstChild) {
// It has at least one
}
o la hasChildNodes()funzione:
if (element.hasChildNodes()) {
// It has at least one
}
o di lengthproprietà di childNodes:
if (element.childNodes.length > 0) { // Or just `if (element.childNodes.length)`
// It has at least one
}
Se vuoi conoscere solo gli elementi figli (al contrario di nodi di testo, nodi di attributi, ecc.) Su tutti i browser moderni (e IE8 - in effetti, anche IE6) puoi farlo: (grazie Florian !)
if (element.children.length > 0) { // Or just `if (element.children.length)`
// It has at least one element as a child
}
Che si basa sulla childrenproprietà, che non è stato definito in DOM1 , DOM2 , o DOM3 , ma che ha il supporto quasi universale. (Funziona in IE6 e versioni successive e Chrome, Firefox e Opera almeno fino a novembre 2012, quando questo è stato originariamente scritto.) Se supporta i dispositivi mobili meno recenti, assicurati di controllare il supporto.
Se non hai bisogno di IE8 e supporto precedente, puoi anche farlo:
if (element.firstElementChild) {
// It has at least one element as a child
}
Ciò si basa firstElementChild. Ad esempio children, non era nemmeno definito in DOM1-3, ma a differenza childrendi IE non è stato aggiunto fino a IE9.
Se vuoi rimanere fedele a qualcosa di definito in DOM1 (forse devi supportare browser davvero oscuri), devi fare più lavoro:
var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild; child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
hasChildElements = true;
break;
}
}
Tutto ciò fa parte di DOM1 e supportato quasi universalmente.
Sarebbe facile racchiudere questo in una funzione, ad esempio:
function hasChildElement(elm) {
var child, rv;
if (elm.children) {
// Supports `children`
rv = elm.children.length !== 0;
} else {
// The hard way...
rv = false;
for (child = element.firstChild; !rv && child; child = child.nextSibling) {
if (child.nodeType == 1) { // 1 == Element
rv = true;
}
}
}
return rv;
}
divha elementi divcon una classe specifica dire xyz?
for (child = element.firstChild; child; child = child.nextSibling ), votato. Grazie TJ
element.firstChildche non sia nullquando element.children.lengthè 0: firstChilde ciò si riferisce a nodi inclusi elementi, nodi di testo, note di commento, ecc .; childrenè puramente un elenco di elementi figlio. Sui browser moderni puoi usare firstElementChildinvece.
Come menzionato da slashnick e bobince, hasChildNodes()restituirà true per gli spazi (nodi di testo). Tuttavia, non volevo questo comportamento e ha funzionato per me :)
element.getElementsByTagName('*').length > 0
Modifica : per la stessa funzionalità, questa è una soluzione migliore:
element.children.length > 0
children[]è un sottoinsieme di childNodes[], contenente solo elementi.
Puoi controllare se l'elemento ha nodi figli element.hasChildNodes(). Fai attenzione in Mozilla, questo restituirà vero se lo spazio dopo il tag è quindi necessario verificare il tipo di tag.
Puoi anche fare quanto segue:
if (element.innerHTML.trim() !== '') {
// It has at least one
}
Questo utilizza il metodo trim () per trattare gli elementi vuoti che hanno solo spazi bianchi (nel qual caso hasChildNodesrestituisce true) come vuoti.
Il frammento di documento in ritardo ma potrebbe essere un nodo:
function hasChild(el){
var child = el && el.firstChild;
while (child) {
if (child.nodeType === 1 || child.nodeType === 11) {
return true;
}
child = child.nextSibling;
}
return false;
}
// or
function hasChild(el){
for (var i = 0; el && el.childNodes[i]; i++) {
if (el.childNodes[i].nodeType === 1 || el.childNodes[i].nodeType === 11) {
return true;
}
}
return false;
}
Vedi:
https://github.com/k-gun/so/blob/master/so.dom.js#L42
https://github.com/k-gun/so/blob/master/so.dom.js # L741
Prova la proprietà childElementCount :
if ( element.childElementCount !== 0 ){
alert('i have children');
} else {
alert('no kids here');
}
Una isEmpty( <selector> )funzione riutilizzabile .
Puoi anche eseguirlo verso una raccolta di elementi (vedi esempio)
const isEmpty = sel =>
![... document.querySelectorAll(sel)].some(el => el.innerHTML.trim() !== "");
console.log(
isEmpty("#one"), // false
isEmpty("#two"), // true
isEmpty(".foo"), // false
isEmpty(".bar") // true
);
<div id="one">
foo
</div>
<div id="two">
</div>
<div class="foo"></div>
<div class="foo"><p>foo</p></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
ritorna true(ed esce dal ciclo) non appena un elemento ha un qualsiasi tipo di contenuto oltre a spazi o nuove righe.
<script type="text/javascript">
function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked)
{
//debugger;
var selectedNode = igtree_getNodeById(nodeId);
var ParentNodes = selectedNode.getChildNodes();
var length = ParentNodes.length;
if (bChecked)
{
/* if (length != 0) {
for (i = 0; i < length; i++) {
ParentNodes[i].setChecked(true);
}
}*/
}
else
{
if (length != 0)
{
for (i = 0; i < length; i++)
{
ParentNodes[i].setChecked(false);
}
}
}
}
</script>
<ignav:UltraWebTree ID="uwtPBSTree" runat="server"..........>
<ClientSideEvents NodeChecked="uwtPBSTree_NodeChecked"></ClientSideEvents>
</ignav:UltraWebTree>
childrenera stato aggiunto solo in DOM4. Sapendo che era supportato in qualsiasi browser noto, ho pensato che fosse praticamente DOM0 / 1.