element.hasChildNodes

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

La méthode Node.hasChildNodes() renvoie un Boolean indiquant si le noeud actuel possède des nœuds enfants ou non.

Syntaxe

js
bool = node.hasChildNodes();

Valeur de retour

Un Boolean qui est true si le nœud a des nœuds enfants, et false dans le cas contraire.

Exemple

js
let foo = document.getElementById("foo");

if (foo.hasChildNodes()) {
  // Faire quelque chose avec 'foo.childNodes'
}

Prothèse d'émulation

js
(function (prototype) {
  prototype.hasChildNodes =
    prototype.hasChildNodes ||
    function () {
      return !!this.firstChild;
    };
})(Node.prototype);

Il y a différentes façons de déterminer si le noeud a un noeud enfant :

  • node.hasChildNodes()
  • node.firstChild != null (ou simplement node.firstChild)
  • node.childNodes && node.childNodes.length (ou node.childNodes.length > 0)

Spécifications

Specification
DOM
# ref-for-dom-node-haschildnodes①

Compatibilité des navigateurs

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
hasChildNodes

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Voir aussi