Test input

 

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

🖋️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

Le classique "Trier"

 https://github.com/dupontdenis/tri.git

L'idée est de trié un tableau en mémoire et de repercuter sur le DOM le changement.


https://dupontdenis.github.io/tri/

composedPath().

 


document.body.addEventListener("click", (eventObject) => { let tabulation = "".padEnd(eventObject.composedPath().length, "▶️"); eventObject.composedPath().forEach((elt) => { document.body.insertAdjacentHTML( "beforeEnd", `<p>Clicked on: ${tabulation} ${elt.nodeName ? elt.nodeName : "Window"}` ); tabulation = tabulation.slice(0, -1); }); });


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

Be a candidate

 

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

insertion dans le DOM : comparaison

  1. <body>
  2.     <script>
  3.         function strToDom(str){
  4.             return document.createRange().createContextualFragment(str).firstChild;
  5.         }
  6.         const mydiv = strToDom(`<div class="div">document.createRange().createContextualFragment</div>`);
  7.         document.body.appendChild(mydiv);

  8.         document.body.insertAdjacentHTML(`afterBegin`,`<div class="div"> document.insertAdjacentHTML</div>`)
  9.     </script>
  10. </body> 

observer

Voici un fichier qui permet de jouer avec l'inspecteur et de vérifier la saisie !

👉https://github.com/dupontdenis/inspecter

  window.onload = function() { 

        let target = document.getElementById("target"),
          response = document.getElementById("response");
        let observer = new MutationObserver(mutations => {
          mutations.forEach(mutation => {
            response.style.display =
              target.style.backgroundColor === "red" ? "block" : "none";
          });
        });
        let observerConfig = {
          attributes: true
        };
        observer.observe(target, observerConfig);
      };


    <div id="background-color">
      <p id="target">Add A Background Color To Me!</p>
      <aside id="response" class="success" style="display:none">
        Success!
      </aside>
    </div>

fonction fléchée


const $ = document.querySelector;
// TypeError: Illegal invocation
const el = $('.some-element');
const $ = document.querySelector.bind(document);
// Or:
const $ = (...args) => document.querySelector(...args);

Parcours du DOM : générateur

 <!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <ul>
    <li>hello 1</li>
    <li>hello 2</li>
    <li>hello 3</li>
  </ul>
  <script>
    function* search(node) {
      if (!nodereturn;
      yield node;
      yield* search(node.firstChild);
      yield* search(node.nextSibling);
    }
    document.body.insertAdjacentHTML("beforeend"`<h1> the DOM`)
    const nodes = [];
    for (let node of search(document.body)) {
      if (node.localNamenodes.push(node.localName)
    }
    document.body.insertAdjacentHTML("beforeend"nodes)

  </script>
</body>

</html>

data-set

Exemple 1

  1. <button data-toggle-id="calendar">
  2.   Show calendar
  3. </button>

  4. <form id="calendar" hidden>
  5.   mois de mai !
  6. </form>


  1.   document.addEventListener('click', function(event) {
  2.     let id = event.target.dataset.toggleId;
  3.     if (!id) return;

  4.     let elem = document.querySelector(`'#${id}'`);
  5.     elem.hidden = !elem.hidden;
  6.   });


https://jsbin.com/wagipuj/edit?html,js,output

Exemple 2

  1. <div id="menu">

  2.   <button data-action="save">Save</button>

  3.   <button data-action="load">Load</button>

  4.   <button data-action="search">Search</button>

  5. </div>


  1. class Menu {

  2.     constructor(elem) {

  3.       this._elem = elem;

  4.       

  5.     }


  6.     save() {

  7.       alert('saving');

  8.     }


  9.     load() {

  10.       alert('loading');

  11.     }


  12.     search() {

  13.       alert('searching');

  14.     }


  15.     onClick(event) {

  16.       let action = event.target.dataset.action;

  17.       if (action) {

  18.         this[action]();

  19.       }

  20.     };

  21.   }


  22.   new Menu(menu);

https://jsbin.com/dufunaf/5/edit?html,css,js,console,output

Evolution : comparaison

 


node

element

function buildTable(data) {

    var table = document.createElement("table");

  

    var fields = Object.keys(data[0]);

  console.log(fields);

    var headRow = document.createElement("tr");

    fields.forEach(function(field) {

      var headCell = document.createElement("th");

      headCell.textContent = field;

      headRow.appendChild(headCell);

    });

    table.appendChild(headRow);


    data.forEach(function(object) {

      var row = document.createElement("tr");

      fields.forEach(function(field) {

        var cell = document.createElement("td");

        cell.textContent = object[field];

        if (typeof object[field] == "number")

          cell.style.cssText = "background-color:black;color:white;text-align:right;"

        row.appendChild(cell);

      });

      table.appendChild(row);

    });


    return table;

  }


  document.body.appendChild(buildTable(PERSON));


function buildTable(data) {

  const table = document.createElement("table"),

    fields = Object.keys(data[0]);


  let template = `<tr><th>${fields[0]}</th><th>${fields[1]}</th><th>${fields[2]}</th></tr>`;

  table.insertAdjacentHTML("afterBegin", template);


  for (let { name, age, country } of data) {

    template = `<tr><td>${name}</td><td>${age}</td><td>${country}</td></tr>`;

    table.insertAdjacentHTML("beforEEnd", template);

  }

  return table;

}


document.body.appendChild(buildTable(PERSON));


code

code


high level function

   function elt(name, attrs, ...children) {
     let dom = document.createElement(name);
     for (let attr of Object.keys(attrs)) {
       dom.setAttribute(attr, attrs[attr]);
     }
     for (let child of children) {
       dom.appendChild(child);
     }
     return dom;
   }

let text = document.createTextNode("topc");

let u = elt("p",{},...[text]);

document.querySelector(".test").appendChild(u);


const tab = ["lun","mard","mercredi"];


let v = elt("div",{},...tab.map( (jour)=> {
  let p = elt("p",{class:"red"})
  p.innerHTML = jour;
  return p;
} ));

document.querySelector(".map").appendChild(v);


En action

à comparer avec

Différence entre screenX, clientX, pageX


yellow Screen → the full screen of the monitor (screenX/Y)
Position will always be relative to the physical screen's viewport.

Blue Client → the client viewport of the browser (clientX/Y)
If you click in the left top corner the value will always be (0,0) independent on scroll position.

Red Document → the complete document/page (pageX/Y)
Note that pageX/pageY on the UIEvent object are not standardized.

All values are in pixels.

screen snapshot with extended page illustration


Simulateur



https://jsbin.com/dilumuz/3/edit?html,css,js,console,output

attachShadow : isole le CSS

append ... en action

  <ul id="tree">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>

Array.from(tree.querySelectorAll('li'),
     ( li ) => {
                       let span = document.createElement('span');
                       li.prepend(span);
                       span.append(span.nextSibling);
                    }
)

Le code précédent transforme chaque élément de la liste comme suit :

<ul class="tree" id="tree">
    <li><span>item 1</span></li>
    <li><span>item 2</span></li>
    <li><span>item 3</span></li>
</ul>

Dom / Node / Element

Voici le vocabulaire a connaitre pour se déplacer dans le DOM/élément !


On pourra utiliser également le vocabulaire suivant au niveau Nœud  !