からJavaScriptを構築する:ドキュメント.クラス名


私は現在、ソフトウェアエンジニアとしての最初の就職活動に飛び込んでいます.インタビューはJavaScriptで行われ、2つの質問から成りました.最初はかなり標準的なアルゴリズムの質問でしたが、2番目はとてもおもしろかったですdocument.getElementByClassName ゼロからの方法.私は以前に何度も使っていたメソッドを構築して、DOM操作とJavascriptの全体の理解を改善した.この記事では、私は私が思い付いた解決策を通してあなたを歩かせます.

目次
  • Table of Contents
  • Goal
  • Example
  • Plan

  • Code
  • Step 1: Set up the main function
  • Step 2: Write the recursive helper function
  • Step 3: Put it all together
  • Step 4: Add to the HTML Element prototype
  • References

  • ゴール
    目標は、機能的に同等のバージョンを作成することです document.getElementByClassName . これを行うには、以下の機能が必要です.
  • 任意のHTML要素で呼び出すことができます
  • つの引数、文字列、クラス名の任意の数を含みます.
  • 渡されるすべてのクラス名にマッチするすべての要素を返します.
  • 関数が呼び出された要素の子要素のみを返す


  • <html>
    <body>
        <div class='parent'>
            <p class='hello'>hello world 1</p>
            <p class='hello'>hello world 2</p>
            <p class='hello'>hello world 3</p>
            <p class='hello'>hello world 4</p>
        </div>
    </body>
    </html>
    
    const parent = document.getElementsByClassName('parent')
    // =>    <div class='parent'></div>
    
    const helloWorlds = document.getElementsByClassName('hello')
    // => [  <p class='hello'>hello world 1</p>,
    //       <p class='hello'>hello world 2</p>,
    //       <p class='hello'>hello world 3</p>,
    //       <p class='hello'>hello world 4</p>  ]
    

    計画
    まず、関数の概念を作成する必要があります.
  • マッチするすべての要素を格納する配列を作成します.
  • クラス名の主要素のすべての直接子孫を確認する
  • を返します.
  • それらの子供たちのすべてを同じ方法でチェックしてください
  • もう子供がなくなるまで繰り返す
  • この計画に基づいて、再帰的なヘルパー関数を作成する必要があります.このヘルパー関数をmain関数内で呼び出します.main関数の戻り値は要素の配列でなければなりません.これは、先頭の空の配列として宣言し、移動するときに要素を追加します.
    今、我々はしっかりした計画を持って、コーディングを取得しましょう!

    コード

    ステップ1:主な機能を設定します
    ここでは、私たちの主な機能を定義します.本体では、2つの変数を定義します.elements , 一致するクラス名を持つすべての要素が追加される配列です.firstChildren , 要素のすべての子関数が呼び出されます.後者については、JavaScriptの .children() メソッドを返します.HTMLCollection それが呼ばれるノードのすべての子要素を含むこと.このHtmlCollectionは配列のように扱うことができます.
    function getElementsByClassName2(classNameStr) {
    
       const elements = [] // the array we will add matching elements to
       const firstChildren = this.children // all the children of the element the function is called on
    
       return elements
    }
    

    ステップ2 :再帰的なヘルパー関数を書く
    エーrecursive function ヘルパー関数は、いくつかのコードをアトリビュートし、再利用可能で読みやすくするための関数です.
    function getElementsByClassName2(classNameStr) {
    
       function checkChildren(child) {
    
          // check if the child has a matching class. If so, push the the elements array
          if (child.classList.contains(className)) {
             elements.push(child)
          }
    
          // check if that child has children of its own. If so, call checkChildren one each child
          if (child.children) {
             const children = child.children
             children.forEach(checkChildren)
         }
       }
    
    }
    

    ステップ3:すべてを一緒に置く
    今、私たちはcheckChildren 各方法firstChildren . この関数が実行された後、我々の要素配列は、一致する要素のすべてを含む必要があります!
    function getElementsByClassName2(classNameStr) {
    
       const elements = []
       const firstChildren = this.children
    
       function checkChildren(child) {
    
          if (child.classList.contains(className)) {
             elements.push(child)
          }
    
          if (child.children) {
             const children = child.children
             children.forEach(child => checkChildren(child))
         }
       }
    
       // call the checkChildren method on the firstChildren
       firstChildren.forEach(child => {
          checkChildren(child)
       })
    
        return elements
    }
    

    Step 4 : HTML要素プロトタイプを追加する
    最後に、HTML関数でこの関数を呼び出すことができるように、HTML要素に追加する必要がありますprototype .
    HTMLElement.prototype.getElementsByClassname2 = getElementsByClassName2
    
    閉じるこの動画はお気に入りから削除されています.新しい方法getElementsByClassName2 今ではオリジナルと同じ機能を持っていますgetElementsByClassName . 私はあなたが興味深いと有益なこのプロセスを見つけたことを望む!
    あなたが記事を楽しんでいるならば、ここで、または、さえずりの上で私に続いてください

    参考文献
  • MDN Docs: Document.getElementsByClassName()
  • JavaScript.info: Recursion and Stack
  • MDN Docs: ParentNode.children()
  • MDN Docs: HTMLCollection
  • Medium: Prototypes in Javascript - Rupesh Mishra