Développement web il3

JavaScript & DOM

JavaScript hier

JavaScript aujourd’hui

*Script

JavaScript

Caractéristiques du langage

Fonctions

escape(), unescape(), isFinite(), isNaN(),
parseFloat(), parseInt(), Number(), String(), 
eval(), ...

JavaScript dans la page web

<div id="intro" onclick="change();" />
<script type="text/javascript">
    document.getElementById("intro").onclick = change;
</script>
<script type="text/javascript" src="script02.js"></script> 

language="JavaScript" est déprécié et type vaut par défaut text/javascript.

The type attribute gives the language of the script or format of the data. […] The default, which is used if the attribute is absent, is “text/javascript”.

HTML5: script

Unobstrusive JS

document.addEventListener("DOMContentLoaded", function() {
    document.getElementById('date').addEventListener("change", validateDate);
};
    <input type="text" name="date" id="date" />

It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.

MDN: DOMContentLoaded

Node.js / Deno

DOM

DOM

<html>
<head>
   <title>My title</title>
</head>
<body>
    <h1>A heading</h1>
    <a href="#">Link text</a>
</body>
</html>
DOM tree

L’objet Document

    querySelector(), querySelectorAll(),
    getElementById(), getElementsByTagName(), getElementsByClassName(), 
    createElement(), createTextNode()
    insertBefore(child), appendChild(child),
    removeChild(child), replaceChild(new,old)

Ajouter un noeud

function addNode() {
     var inText = document.getElementById("textArea").value;
     var newText = document.createTextNode(inText);

     var newGraf = document.createElement("p");
     newGraf.appendChild(newText);

     var docBody = document.getElementsByTagName("body")[0];
     docBody.appendChild(newGraf);
}

Supprimer un nœud

function delNode() {
   var allGrafs = document.getElementsByTagName("p");

   if (allGrafs.length > 1) {
      var lastGraf = allGrafs.item (allGrafs.length-1);
      lastGraf.parentNode.removeChild(lastGraf);
   }
   else {
      console.error("Nothing to remove!");
   }
}

Insérer un nœud

function insertNode() {
     var newText = document.createTextNode("New Text");
     var newGraf = document.createElement("p");
     newGraf.appendChild(newText);
    
     var divMod = document.getElementsByTagName("div")[0];
     var allGrafs = divMod.getElementsByTagName("p");
     var oldGraf = allGrafs.item(0);             // position

     divMod.insertBefore(newGraf,oldGraf);
}

Avec jQuery

    var noeud = $('<p>Nouveau texte</p>');  // create node
    $("body").append(noeud);                // après le dernier fils
    var noeud = $("p"); // select node(s)
    noeud.remove();

Références

Sources