ホームページ  >  記事  >  ウェブフロントエンド  >  フロントエンド開発に不可欠な DOM メソッドを探る

フロントエンド開発に不可欠な DOM メソッドを探る

WBOY
WBOYオリジナル
2024-08-01 06:46:53385ブラウズ

Chimezie Innocent 作✏️

可能な限り最高のエクスペリエンスを提供するには、ユーザーがお気に入りのオンライン ストアやその他のサイトを閲覧する際のアクションに合わせて動的に動作するスムーズな Web ページが鍵となります。しかし、ユーザーがこの重要なコンテンツすべてにオンデマンドでアクセスするための基盤として機能するものは何でしょうか?

HTML を使用して記述されたテキスト ファイルは、ユーザーが期待する動的コンテンツの表示方法を Web ブラウザーに指示します。Web ページのコンテンツにアクセスして変更する方法は、ドキュメント オブジェクト モデル (DOM) と呼ばれます。

Exploring essential DOM methods for frontend development

DOM は HTML 構造と JavaScript の間のギャップを埋め、Web ページを動的に変更したり操作したりできるようにします。いくつかのメソッドを使用して DOM を変更したり操作したりすることができ、これらのメソッドは DOM メソッドとして知られています。 DOM メソッドは、Web ページとの動的な対話を可能にし、ユーザーにスムーズな Web ブラウジング エクスペリエンスを提供するため、フロントエンド開発にとって非常に重要です。

この記事で説明する特定の DOM メソッドをマスターすると、豊かなユーザー エクスペリエンスを作成できるようになります。 DOM メソッドは多数ありますが、この記事では、フロントエンド開発とそれに関連するユースケースに不可欠な DOM メソッドのみを取り上げます。さらに、記事の下部に、ここで説明する DOM メソッドの名前、構文、機能をまとめた表を用意しました。

いくつかの DOM メソッドは同様のタスクに使用されるため、それらをグループ化すると、それらが何を行うのかをよりよく理解できるようになります。また、これらの DOM メソッドの使用例を見て、それらを使用する最適な方法を確認します。

クエリまたは DOM メソッドの選択を調べる

これらの DOM メソッドは、DOM ツリーまたは HTML 内の特定の要素を検索してアクセスするために使用されます。

querySelector()

クエリメソッドリストの最初は、querySelector です。このメソッドは、指定された CSS セレクターまたはセレクターのグループに一致する最初の要素を選択します。一致するものが見つからない場合は、null を返します。すべての有効な CSS セレクターを使用して要素を検索します。

以下の例を見てみましょう:

// index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World</h1>
    <div class="first">
      <p>This is a paragraph</p>
    </div>
    <div class="first">
      <p>This is a paragraph</p>
    </div>
    <div id="second">
      <p>Another paragraph</p>
    </div>
  </body>
  <script src="/script.js"></script>
</html>

上記のコードは、h1 タグ、3 つの div 要素、および 3 つの段落 p タグを含むページをレンダリングします。このサンプル コードは、使用例のほとんどで使用します。

お気づきかと思いますが、div のうち 2 つは class 属性と同じクラス名を持ち、もう 1 つは ID 属性を持っています。

前に説明したように、querySelector は CSS セレクターに一致する最初の要素を見つけます。これは、クラス、ID、さらにはそれらのタグを利用して、このメソッドで要素を検索できることを意味します。以下を参照してください:

// script.js

const element = document.querySelector("h1").textContent;
console.log(element);

const element2 = document.querySelector(".first").innerHTML;
console.log(element2);

const element3 = document.querySelector("#second").innerHTML;
console.log(element3);

上記のことから、タグ名、クラス、ID 属性を使用して要素を検索しています。コンソール上の出力は次のようになります: Exploring essential DOM methods for frontend development

上記のように、div の完全な innerHTML を取得しながら textContent をログに記録しているため、「Hello World」のみを取得しています。また、同じクラス名の div が 2 つありますが、コンソール ログには 1 つだけが表示されます。これは、querySelector が指定された CSS セレクターの最初の要素のみを取得するためです。

もう 1 つ: さらに進んで、querySelector メソッドで複雑なセレクターを使用することもできます。すべての CSS セレクター文字列が有効であるため、否定セレクターを使用することもできます。 HTML にわずかな変更を加える方法については、以下の使用例を参照してください:

// index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Hello World</h1>

    <div class="first">
      <p class="paragraph main">This is a paragraph</p>
    </div>
    <div class="first">
      <p class="paragraph">This is a second paragraph</p>
    </div>
    <div id="second">
      <p>Another paragraph</p>
    </div>
  </body>
  <script src="/script.js"></script>
</html>

最初の div の p タグにクラス属性の段落を追加し、最初の p タグにもう 1 つのクラス main を追加しました。

// script.js

const element = document.querySelector("div p").textContent;
console.log(element);

const element2 = document.querySelector("div.first .paragraph:not(.main)").textContent;
console.log(element2);

これは結果の出力です: Exploring essential DOM methods for frontend development 最初に親要素を指定してから DOM 階層をさらに下に進むことで DOM 子要素にアクセスできるため、div が親ノードである div p を使用して最初の段落にアクセスできます。 p は子ノードです。

さらに、2 番目のクエリでは、今回は最初の段落ではなく 2 番目の段落を取得しました。これは、CSS セレクターでメインクラスではない最初の要素を取得しているためです。

querySelectorAll()

クエリ メソッド リストの 2 番目は、querySelectorAll です。この DOM メソッドは、指定されたセレクターまたはセレクターのグループに一致するすべての DOM 要素を含む静的 NodeList を取得または返します。このメソッドは、同じクラスの複数の要素を選択またはクエリする場合に便利です。

注: NodeList は単にノードのコレクションです。 querySelectorAll() は静的な NodeList を返します。これは、DOM 内の変更がコレクションのコンテンツに影響を与えないことを意味します。

以下の使用例を見てください:

// script.js

const element = document.querySelectorAll("div");
console.log(element);

const element2 = document.querySelectorAll(".first");
console.log(element2);

console.log(typeof element)

As explained, querySelectorAll() will return a node list of all the divs. Additionally, we are checking what type of primitive the returned element is, and as expected, when we console log the element’s type, it returns an object: Exploring essential DOM methods for frontend development After getting the node list, we can loop through the elements using any of the loops like map, forEach, and so on to make whatever changes we want:

// script.js

const element = document.querySelectorAll(".first");
element.forEach(paragraph => paragraph.innerHTML="This is great")

The below image shows how we are just changing the text content of the p tags — nothing fancy: Exploring essential DOM methods for frontend development  

getElementById()

This DOM method retrieves the element with a specific ID. This is best used when you need to select a single unique element quickly since IDs are required to be unique if specified. Unlike the querySelector and querySelectorAll, you don’t need to add the # selector when using the getElementById() method:

// script.js

const element = document.getElementById("second").textContent;
console.log(element);

This will return the element with the ID specified. The output of the console will be: Exploring essential DOM methods for frontend development  

getElementsByClassName()

This DOM method returns an array-like object containing all the child elements with the specified class names. Each element in the object can be accessed by its index:

// script.js

const element = document.getElementsByClassName("first");
console.log(element)

This will return all elements with the class name first. The output on the console will be: Exploring essential DOM methods for frontend development   Similar to the querySelectorAll, this method is useful when you want to apply changes to multiple elements with the same class name. Let’s change the color:

// script.js

const element = document.getElementsByClassName("first");
Array.from(element).map((el) => (el.style.color = "red"));

In your webpage, the output becomes: Exploring essential DOM methods for frontend development  

getElementsByTagName()

This method is ideal for operations on a specific element as it returns an HTML collection of elements with specified tag names.

// script.js

const element = document.getElementsByTagName("p");
console.log(element)

On the console, the output will be logged as the following: Exploring essential DOM methods for frontend development   Also, since element returns an array-like object, you can perform multiple changes at once by using any of the loop operators. Each element can also be accessed by its index, which starts at 0.

// script.js

const element = document.getElementsByTagName("p");
Array.from(element).map((el) => (el.style.color = "red"));

const last_item = element[2].textContent
console.log(last_item); // Another paragraph

The output results in the below: Exploring essential DOM methods for frontend development  

Methods for getting and setting content

These DOM methods accomplish two uses — they help us retrieve information from elements and allow us set the content dynamically.

innerHTML

This method retrieves and sets the HTML content of an element. It specifically retrieves the HTML inside the element, including text and tags, and can also replace the HTML.

Let’s employ one h1 tag for this use case:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="h1">Hello World</h1>
  </body>
  <script src="/script.js"></script>
</html>

Next, we’ll write the following in our script:

// script.js

const element = document.getElementById("h1");
console.log(element.innerHTML);

element.innerHTML = "<h5>New Content</h5>";
console.log(element.innerHTML);

In our console, we will get the “Hello World” since we are retrieving the HTML content. Next, we’ll change the HTML tag to an h5 tag with new content. When we retrieve the new element, we see it has changed: Exploring essential DOM methods for frontend development  

textContent

As the name implies, this method gets and sets the text content of the node and its descendants. The best use case for this method is for getting and replacing the text content of an element without the HTML tags.

Let’s look at the use case below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="h1">This is <span>some</span> text!</h1>
  </body>
  <script src="/script.js"></script>
</html>

The above code renders a h1 tag with the text: “This is some text”

// script.js

const element = document.getElementById("h1");
console.log(element.textContent);

// change the content
element.textContent = "This is a new text";
console.log(element.textContent);

In our script.js file, we use the query method getElementById to retrieve the h1 tag. Next, we use the textContent method to change the content of our h1 text to “This is a new text”.

The output becomes the following: Exploring essential DOM methods for frontend development  

Attribute and style manipulation methods

This group includes methods that allow you to modify DOM elements' attributes, properties, and content.

add

This method adds a specified class to an element’s class list. You can use the add method to toggle CSS classes to change an element’s appearance.

In our HTML, let’s add a style:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .newClass {
        color: green;
      }
    </style>
  </head>
  <body>
    <h1 id="h1">This is <span>some</span> text!</h1>
  </body>
  <script src="/script.js"></script>
</html>

The result is just a class with a green text color. Nothing happens when we load our page because we haven’t assigned the style to any element yet. Next, let’s assign the style to our h1 element using the add method:

// script.js

let element = document.getElementById('h1');
element.classList.add('newClass');

Reload your page and you will see that the header’s color has changed: Exploring essential DOM methods for frontend development  

remove

This method removes a specified class from an element’s class list. The remove method takes out a CSS class to change the element’s appearance back to default.

// script.js

let element = document.getElementById('h1');
element.classList.remove('newClass');

createElement

This method creates a new HTML element with the specified tag name (e.g., div, p) and is essential for dynamically building elements on the page. You can create new paragraphs, buttons, or any other HTML element as needed:

// script.js

let newDiv = document.createElement('div');

appendChild

This method inserts a child element as the last child of a parent element and adds newly created elements (with the createElement method) to an existing element in the DOM; this allows us to build complex structures dynamically. After a child element or node has been created, use appendChild to add the new element to the end of the list of children of the specified node.

See example below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1 id="h1">This is <span>some</span> text!</h1>
    <div id="div"></div>
  </body>
  <script src="/script.js"></script>
</html>

This is what we have before we append any new element: Exploring essential DOM methods for frontend development   Next, let’s create a new element and add it to the empty div above.

// script.js

const parentNode = document.getElementById("div");
const textElement = document.createTextNode("This is a text node");
const pTag = document.createElement("p");
const newElement = pTag.appendChild(textElement);
parentNode.appendChild(newElement);

We included a text node and appended it to a p tag that we created using the createElement method. Next, we append the p tag to our div, which we have targeted using the getElementById method. The output then shows on our page as seen below: Exploring essential DOM methods for frontend development  

setProperty

This method sets a specific style property on an element (e.g., color, font-size) and provides granular control over element styles. This lets you dynamically change the appearance of elements based on user interactions and other conditions.

The syntax of the setProperty method is:

element.style.setProperty(propertyName, value)

Where propertyName is the CSS property we want to target, and value indicates the values of the CSS property.

Look at the example below:

// script.js

const element = document.getElementById("h1");
element.style.setProperty("color", "red");

In the code above, we retrieve our element using its id: h1. Next, we use our setProperty method to change or set the color of the text content to red.

On our page, the output of the code is as shown: Exploring essential DOM methods for frontend development  

Event or event handling methods

Event methods handle and manipulate events, enabling interactivity in webpages. The essential methods under this category include addEventListener() and removeEventListener().

addEventListener()

This is one of the most important DOM methods that you will use. The method attaches an event listener to an element, allowing the element to respond to specific user interactions. An event is anything that happens in your system, program, or webpage. An event could be a click, a load, a focus, a keydown, or keyup event, and so on.

The addEventListener attaches to an element, a listener that listens to any of these events, and when the events happen, the listener triggers a specified interaction with that element.

The syntax for the addEventListener is the following:

addEventListener(type, listener)

Where type is the type of event you want to listen to, listener is the object that receives a notification or implements the event you want.

In our HTML, let’s add a button element:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <button>Click Me!</button>
  </body>
  <script src="/script.js"></script>
</html>

In our JavaScript file, let’s add a listener that shows a “Hello World” alert whenever the button is clicked:

// script.js

const buttonElement = document.querySelector("button");
buttonElement.addEventListener("click", () => {
  alert("Hello World");
});

Using the querySelector, we get the button element. Then, we attach a click event to it. Whenever the button is clicked, our listener function is executed:

The output becomes:

Webpage with ‘Hello World’ heading, three paragraphs, a ‘Click Me!’ button, and an alert box saying ‘Hello World’.  

removeEventListener()

Similar to the addEventListener, this method removes an event listener from an element.

The syntax for this method is below:

removeEventListener(type, listener)

Where type is the type of event you are listening to and listener is the function that implements the event you want.

Let’s see a real-world use case to see this method in action. Copy and replace your HTML with the code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Canvas Drawing</h1>
    <canvas
      id="drawingCanvas"
      width="500"
      height="500"
      style="border: 2px solid black"
    ></canvas>
    <div>
      <button id="startDrawingBtn">Start Drawing</button>
      <button id="stopDrawingBtn">Stop Drawing</button>
    </div>
  </body>
  <script src="/script.js"></script>
</html>

It’s nothing fancy — we have a canvas element we can draw on and two buttons that allow us to draw on the canvas or not. The main interactivity comes in our JavaScript below:

// script.js

let startButton = document.getElementById("startDrawingBtn");
let stopButton = document.getElementById("stopDrawingBtn");
let canvas = document.getElementById("drawingCanvas");
let ctx = canvas.getContext("2d");
let drawing = false;

// draw function
function draw(event) {
  if (!drawing) return;
  ctx.lineWidth = 5;
  ctx.lineCap = "round";
  ctx.strokeStyle = "blue";
  ctx.lineTo(
    event.clientX - canvas.offsetLeft,
    event.clientY - canvas.offsetTop
  );
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(
    event.clientX - canvas.offsetLeft,
    event.clientY - canvas.offsetTop
  );
}

// mousedown handler
function handleMouseDown(event) {
  drawing = true;
  ctx.beginPath();
  canvas.addEventListener("mousemove", draw);
}

// mouseup handler
function handleMouseUp() {
  drawing = false;
  ctx.beginPath();
  canvas.removeEventListener("mousemove", draw);
}

// Function to start drawing
function startDrawing() {
  canvas.addEventListener("mousedown", handleMouseDown);
  canvas.addEventListener("mouseup", handleMouseUp);
}

// Function to stop drawing
function stopDrawing() {
  drawing = false;
  canvas.removeEventListener("mousedown", handleMouseDown);
  canvas.removeEventListener("mouseup", handleMouseUp);
}

// Our event listeners
startButton.addEventListener("click", startDrawing);
stopButton.addEventListener("click", stopDrawing);

We get our button and canvas elements using the getElementById method. Next, we have three events: mouseup, mousedown, and mousemove. These events will be used for our canvas drawing.

We define two functions to handle our drawing state:

  • In the startDrawing function, we attach mousedown and mouseup events to the canvas to enable drawing when the mouse is held down and dragged. mousemove is used within mousedown to draw as the mouse moves
  • In the stopDrawing function, we remove the mousedown, mouseup, and mousemove events to stop drawing using the removeEventListener method

Finally, we attach click events to our buttons to trigger startDrawing or stopDrawing event functions when clicked.

The output becomes the following: Exploring essential DOM methods for frontend development  

DOM methods cheat sheet

Below is a summary of the different DOM methods we have seen so far in this article. The table includes the syntax and function of each method:

Name Syntax Function
Query or Select methods document.querySelector(selector) Selects the first element that matches the specified CSS selector.
document.querySelectorAll(selector) Selects all element that matches the specified CSS selector. Returns a `NodeList`.
document.getElementById(id) Selects an element by its ID.
document.getElementsByClassName(className) Selects all elements that have the specified class name. Returns an HTMLCollection.
document.getElementsByTagName(tagName) Selects all elements that have the specified tag name. Returns an HTMLCollection.
Get Content Methods element.innerHTML Gets or sets the HTML content of an element.
element.textContent Gets or sets the text content of an element.
Attribute and Style Manipulation Methods element.classList.add(className) Adds a class to the class list of an element.
element.classList.remove(className) Removes a class from the class list of an element.
document.createElement(tagName) Creates a new element with the specified tag name.
element.appendChild(childNode) Adds or inserts a child element/node as the last child of a parent element.
element.style.setProperty(propertyName, value) Sets a new value to a specific style property on an element.
Event Handling methods element.addEventListener(event, handleFunction) Attaches an event listener to an element, allowing the element to respond to specific user interactions.
element.removeEventListener(event, handleFunction) Removes an event handler that has been attached to an element.

結論

重要な DOM メソッドを検討し、それぞれの使用例を確認しました。これらの DOM メソッドを習得することは、フロントエンド開発者にとって重要であるだけでなく、そうすることで、動的でインタラクティブな Web アプリケーションを作成できるようになります。 DOM 要素のクエリ、コンテンツと属性の操作、イベントとスタイルの処理はすべて、ユーザー エクスペリエンスを効果的に制御および強化するための基本ツールを提供します。

LogRocket: コンテキストを理解することで JavaScript エラーをより簡単にデバッグします

コードのデバッグは常に面倒な作業です。しかし、間違いを理解すればするほど、修正が容易になります。

LogRocket を使用すると、これらのエラーを新しい独自の方法で理解できます。当社のフロントエンド監視ソリューションは、JavaScript フロントエンドに対するユーザーの関与を追跡し、エラーを引き起こしたユーザーの行動を正確に確認できるようにします。

Exploring essential DOM methods for frontend development

LogRocket は、コンソール ログ、ページの読み込み時間、スタック トレース、ヘッダーと本文を含む遅いネットワーク リクエスト/レスポンス、ブラウザーのメタデータ、カスタム ログを記録します。 JavaScript コードの影響を理解するのがこれまでになく簡単になります!

無料でお試しください。

以上がフロントエンド開発に不可欠な DOM メソッドを探るの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。