Pages

Correction DS

myForEach : sujet A

myMap : sujet B

myFilter : sujet C

myMethod

Création de vos outils : 

myForEach

myFilter

DOM TD

 introduction au DOM

l'opérateur &&

const myForEach = (tab, callback) => {
  for (let i = 0; i < tab.length; i++) {
    callback(tab[i], i, tab);
  }
};

const notes = [12, 7, 17, 5, 19];
// 👉 Si la note < 6 on met Ajourné

myForEach(notes, (n, i, t) => n < 7 && (t[i] = "AJ")); 

 

 📦Cas des objets

Le DOM

Calculer la moyenne d'un groupe avec des étudiants absents

📒 Selecteur = p

const students = document.querySelectorAll("p");

let sum = 0;
let count = 0;

for (const student of students) {
  const mark = Number(student.dataset.mark);

  if (!isNaN(mark)) {
    sum += mark;
    count++;
  }
}


const average = count
  ? (sum / count).toFixed(2)
  : "Aucune note";

const students = document.querySelectorAll("p");

let sum = 0;
let count = 0;

for (const student of students) {
  const mark = Number(student.dataset.mark);

  if (!isNaN(mark)) {
    sum += mark;
    count++;
  }
}


const average = count
  ? (sum / count).toFixed(2)
  : "Aucune note";

Choix d'un selecteur ! 

// utilisez le bon selecteur
const elements = document.querySelectorAll("[data-mark]");

let sum = 0;

for (const el of elements) {
    sum += Number(el.dataset.mark);
}

const average = sum / elements.length;

;



🤌🏼En action

See the Pen UsetherightSelector by dupont (@dupontcodepen) on CodePen.


En action : github

🥷🏼 En action (L2)

// 🥷🏼utilisation des méthodes en L2

const marks = [...document.querySelectorAll("[data-mark]")]
  .map(p => Number(p.dataset.mark));

const average =
  marks.length ? (marks.reduce((a, b) => a + b) / marks.length).toFixed(2) : "Aucune note";

See the Pen querySelector by dupont (@dupontcodepen) on CodePen

TD DOM

TD de base


Parcours de l'arbre : help

DOM : Start coding !

 

DOM de base

Fonctions de base à tester dans la console de http://dupontcours.free.fr/JavaScript/DOM-javascript/dom.html


🆒Sélectionnez tous les paragraphes

  1. const paragraphes = document.querySelectorAll("p");

Comptez le nombre de paragraphes

  1. const  paragraphes = document.querySelectorAll("p");
  2. console.log( paragraphes.length)

Une boucle sur la selection des paragraphes

  1. const  paragraphes = document.querySelectorAll("p");
  2. for (let p of  paragraphes) {
  3.         console.log(p.innerText.split(" ").length); // count words
  4. }

      1️⃣Ajouter une classe à tous les paragraphes

      1. const  paragraphes = document.querySelectorAll("p");
      2. for (let p of  paragraphes) {
      3.     p.classList.add("second");
      4. }

      🪛Ajoutez un événement click (voir amélioration par délégation)

      1. const paragraphes = document.querySelectorAll("p");
      2. for (let p of paragraphes ) {
      3.   p.addEventListener("click", () => {
      4.     p.classList.toggle("second");
      5.   });
      6. }

      🥇La délégation 

      1. const fun = function (event) {
      2.   const targetElement = event.target; // p or em

      3.   if (targetElement.closest("p")) {
      4.     let para = targetElement.closest("p");
      5.     para.classList.toggle("second");
      6.   }
      7. };

      8. const parent = document.querySelector("body");
      9. parent.addEventListener("click", fun, false);
      🥷Autres exemples de code à tester sur codePen.
      Somme des valeurs contenu dans l'attribut data-code
      1. let value = 0;
      2. for (let para of articles) {
      3.   value+= parseInt(para.dataset.code) // parseInt transforme la valeur en entier !
      4. }
      5. console.log(value)

      Affichez le résultat dans un div.
      1. let value = 0;
      2. for (let para of articles) {
      3.   value+= parseInt(para.dataset.code) // parseInt transforme la valeur en entier !
      4. }
      5. document.querySelector("div").innerText = value


      🔜 Pour la moyenne ! 
      1. const students = document.querySelectorAll("[data-mark]");

      2. const total = [...students].reduce(
      3.   (sum, el) => sum + Number(el.dataset.mark),
      4.   0
      5. );

      6. const average = (total / students.length).toFixed(2);

      7. document.querySelector(".msg").textContent += average;

      🥷🏿parcours

       Parcours à la recherche de texte !


      Rechercher un mot dans une page !

       en action !

      Afficher le DOM dans une page

      Remarque :

      Code avec expReg : en action

      Parcours DOM

       

        https://dupontdenis.github.io/AnimDOM/

      Cours DOM : parcours

       Parcours du DOM

      Ecrire une fonction de parcours du DOM : printDomEle


      🎁
      HTML

      <body>
      article{article $}>section{section $}*2>p{para $}*3(puis Tab)
      </body>


      JS
      fonctions utiles :   console.group(); console.groupEnd();
      on utilise children pour avoir les enfants d'un noeud.
      on utilise for of pour réaliser une boucle

      La fonction est lancée sur le body avec printDomEle(document.body);

      You are ningas ! 🥷🏽

      Dans un groupe, il y a des étudiants [👩🏼‍🦰👦🏿👨‍🦱👨🏽‍🦳👩🏽🧔🏽 👩🏽 ]avec chacun une moyenne.

      Comment écrire que l'on recherche s'il existe un.E étudiant.e abscent (ABI)

      → Réponse  mySome(students, isABI); 


      Dans un panier (basket) 🧺, il y a plein de fruits et des légumes 🍍🍑 🥕🍅🥦🍒🍌🥔🍄🍓🧄🌰🫛.

      Comment écrire que l'on recherche s'il existe un fruit sans pépin (seed) ?

      → Réponse  mySome(basket, isSeedlessFruit); 



      🪛En action


      const basket = [
        { icon: "🍎", hasSeeds: true, color: "red", price: 1.2, category: "fruit" },
        {
          icon: "🥕",
          hasSeeds: false,
          color: "orange",
          price: 0.7,
          category: "vegetable",
        },
        {
          icon: "🍌",
          hasSeeds: false,
          color: "yellow",
          price: 1.0,
          category: "fruit",
        },
        {
          icon: "🥦",
          hasSeeds: false,
          color: "green",
          price: 1.8,
          category: "vegetable",
        },
        { icon: "🍓", hasSeeds: true, color: "red", price: 0.5, category: "fruit" },
        {
          icon: "🍆",
          hasSeeds: true,
          color: "purple",
          price: 2.1,
          category: "vegetable",
        },
        { icon: "🥝", hasSeeds: true, color: "green", price: 1.3, category: "fruit" },
        {
          icon: "🍍",
          hasSeeds: false,
          color: "yellow",
          price: 3.5,
          category: "fruit",
        },
      ];

      const isSeedlessFruit = basketItem =>
              basketItem.category === "fruit" && !basketItem.hasSeeds;

      const hasSeedlessFruit = mySome(basket, isSeedlessFruit); 


      DS

      ---------------------------------------------

      // Basket: a mixed list of fruits and vegetables
      // Each item has properties describing what it is
      // ---------------------------------------------
      const basket = [
        {
          icon: "🍎",
          hasSeeds: true,
          color: "red",
          weight: 180,
          sweetness: 6,
          price: 1.2,
          category: "fruit",
        },
        {
          icon: "🥕",
          hasSeeds: false,
          color: "orange",
          weight: 80,
          sweetness: 4,
          price: 0.7,
          category: "vegetable",
        },
        {
          icon: "🍌",
          hasSeeds: false,
          color: "yellow",
          weight: 120,
          sweetness: 8,
          price: 1.0,
          category: "fruit",
        },
        {
          icon: "🥦",
          hasSeeds: false,
          color: "green",
          weight: 300,
          sweetness: 3,
          price: 1.8,
          category: "vegetable",
        },
        {
          icon: "🍓",
          hasSeeds: true,
          color: "red",
          weight: 25,
          sweetness: 9,
          price: 0.5,
          category: "fruit",
        },
        {
          icon: "🍆",
          hasSeeds: true,
          color: "purple",
          weight: 250,
          sweetness: 2,
          price: 2.1,
          category: "vegetable",
        },
        {
          icon: "🥝",
          hasSeeds: true,
          color: "green",
          weight: 75,
          sweetness: 7,
          price: 1.3,
          category: "fruit",
        },
        {
          icon: "🍍",
          hasSeeds: false,
          color: "yellow",
          weight: 900,
          sweetness: 5,
          price: 3.5,
          category: "fruit",
        },
      ];

      /**
       * Custom implementation of Array.prototype.some()
       * ------------------------------------------------
       * @param {Array} array - the list we want to check
       * @param {Function} fxn - the test function applied to each element
       * @returns {boolean} - true if at least one element passes the test
       *
       * How it works:
       * - Loop through the array
       * - Apply the callback to each element
       * - If the callback returns true → stop and return true
       * - If no element matches → return false
       */
      function mySome(array, fxn) {
        for (let i = 0; i < array.length; i++) {
          if (fxn(array[i])) {
            return true; // Found at least one matching item
          }
        }
        return false; // No match found
      }

      // ------------------------------------------------------
      // Example 1: Check if the basket contains a vegetable
      // Using a classic function expression
      // ------------------------------------------------------
      const hasVegetable = mySome(
        basket,
        function (basketItem) {
          return basketItem.category === "vegetable";
        }
      );
      console.log("Has vegetable?", hasVegetable); // true

      // ------------------------------------------------------
      // Example 2: Same test, but using an arrow function
      // ------------------------------------------------------
      const hasVegetable2 = mySome(
        basket,
        basketItem => basketItem.category === "vegetable"
      );
      console.log("Has vegetable?", hasVegetable2); // true

      // ------------------------------------------------------
      // Example 3: Store the callback in a variable
      // ------------------------------------------------------
      const hasVegetable3 = basketItem => basketItem.category === "vegetable";

      const hasVegetable3Result = mySome(basket, hasVegetable3);

      console.log("Has vegetable?", hasVegetable3Result); // true

      // ------------------------------------------------------
      // Example 4: Check if the basket contains an expensive item
      // ------------------------------------------------------
      const hasExpensiveItem = mySome(
        basket,
        basketItem => basketItem.price > 3
      );
      console.log("Has expensive item?", hasExpensiveItem); // true (🍍)

      // ------------------------------------------------------
      // Example 5: Check if the basket contains a seedless fruit
      // ------------------------------------------------------
      const seedlessFruit = mySome(
        basket,
        basketItem => basketItem.category === "fruit" && !basketItem.hasSeeds
      );
      console.log("Has seedless fruit?", seedlessFruit); // true (🍌, 🍍)

      DS

        

      Integrez cette vidéo dans votre site ! Comment la faire demarrer automatiquement ?

      DOM


      🥷🏿Parcours l'arbre du DOM

      <body>
      <p class="premier">Para 1</p>
      <p><em>second </em> Para 2</p>
      <p id="dernier"> dernier Para</p>
      <!-- je suis un commentaire -->
      </body>

      https://dupontdenis.github.io/parcoursArbreGenerator/


      code : 

      function* search(node) { console.log("➡️ Entrée dans search() avec :", node); if (!node) { console.log("⛔ Node est null, on stoppe ici."); return; } console.log("📤 Yield du node :", node); yield node; console.log("🔽 Appel récursif sur firstChild :", node.firstChild); yield* search(node.firstChild); console.log("➡️ Appel récursif sur nextSibling :", node.nextSibling); yield* search(node.nextSibling); } // document.body.insertAdjacentHTML("beforeend", `<h1> the DOM`); const nodes = []; for (let node of search(document.body)) { console.log("📥 Node reçu dans le for...of :", node); if (node.localName) nodes.push(node.localName); } document.body.insertAdjacentHTML( "beforeend", `<p>${nodes.join("<span> </span>")}</p>` );

      Cours JS


      🥷 https://javascript.info/


      Browser: Document, Events, Interfaces



      LE DOM

       


      Interface/fonctionnalité


      Interface

      Le code de l'interface 


      Fonctionnalité


      Cas de la calculette ! 



      Clonez le code de l'interface




      DOM

       

      🖋️DOM

       

      Travail personel sur le DOM

      Property / MethodDescription
      element.appendChild()Adds a new child node, to an element, as the last child node
      element.attributesReturns a NamedNodeMap of an element's attributes
      element.childElementCountReturns the number of child elements an element has
      element.childNodesReturns a collection of an element's child nodes (including text and comment nodes)
      element.childrenReturns a collection of an element's child element (excluding text and comment nodes)
      element.classListReturns the class name(s) of an element
      element.classNameSets or returns the value of the class attribute of an element
      element.cloneNode()Clones an element
      element.contains()Returns true if a node is a descendant of a node, otherwise false
      element.contentEditableSets or returns whether the content of an element is editable or not
      element.firstChildReturns the first child node of an element
      element.firstElementChildReturns the first child element of an element
      element.getAttribute()Returns the specified attribute value of an element node
      element.getAttributeNode()Returns the specified attribute node
      element.getElementsByClassName()Returns a collection of all child elements with the specified class name
      element.getElementsByTagName()Returns a collection of all child elements with the specified tag name
      element.hasChildNodes()Returns true if an element has any child nodes, otherwise false
      element.idSets or returns the value of the id attribute of an element
      element.innerHTMLSets or returns the content of an element
      element.insertBefore()Inserts a new child node before a specified, existing, child node
      element.lastChildReturns the last child node of an element
      element.lastElementChildReturns the last child element of an element
      element.nextSiblingReturns the next node at the same node tree level
      element.nextElementSiblingReturns the next element at the same node tree level
      element.nodeNameReturns the name of a node
      element.nodeTypeReturns the node type of a node
      element.nodeValueSets or returns the value of a node
      element.parentNodeReturns the parent node of an element
      element.parentElementReturns the parent element node of an element
      element.previousSiblingReturns the previous node at the same node tree level
      element.previousElementSiblingReturns the previous element at the same node tree level
      element.querySelector()Returns the first child element that matches a specified CSS selector(s) of an element
      element.querySelectorAll()Returns all child elements that matches a specified CSS selector(s) of an element
      element.removeAttribute()Removes a specified attribute from an element
      element.removeChild()Removes a child node from an element
      element.replaceChild()Replaces a child node in an element
      element.setAttribute()Sets or changes the specified attribute, to the specified value
      element.setAttributeNode()Sets or changes the specified attribute node
      element.styleSets or returns the value of the style attribute of an element
      element.tagNameReturns the tag name of an element
      element.textContentSets or returns the textual content of a node and its descendants
      nodelist.item()Returns the node at the specified index in a NodeList
      nodelist.lengthReturns the number of nodes in a NodeList

      Solution rendre la money !

       lien

      Rendre la monnaie !


      Il est facile de trouver comment rendre 33€ en utilisant des pièces de 5,3 et 1.

      En effet, il suffit de décomposer 33 sous la forme [ 33 = 5x + 2y + 1z ].