# Walking the DOM

<table><thead><tr><th width="245.95952615992104"></th><th width="188.59345739405245">Definition</th><th>Example</th></tr></thead><tbody><tr><td><mark style="color:blue;"><strong>Create/Remove element</strong></mark></td><td></td><td></td></tr><tr><td><strong>document.createElement(tag)</strong></td><td>To create DOM nodes</td><td><code>document.createElement('div.remove()');</code></td></tr><tr><td><strong>elem.remove()</strong></td><td>remove a node</td><td></td></tr><tr><td><strong>elem.cloneNode(true)</strong></td><td><code>elem.cloneNode(true)</code> creates a “deep” clone of the element – with all attributes and subelements. If we call <code>elem.cloneNode(false)</code>, then the clone is made without child elements.</td><td><code>let div2 =</code> <code>div.cloneNode(true)</code>;</td></tr><tr><td><mark style="color:blue;"><strong>Select element</strong></mark></td><td></td><td></td></tr><tr><td><h4>document.querySelector</h4></td><td>returns the first element for the given CSS selector.</td><td><code>document.querySelector('#ele')</code></td></tr><tr><td><strong>document.getElementById</strong></td><td></td><td><code>document.getElementById('ele')</code></td></tr><tr><td><h4>document.querySelectorAll</h4></td><td>returns all elements inside <code>elem</code> matching the given CSS selector.</td><td><code>document.querySelectorAll('ul > li:last-child');</code></td></tr><tr><td><strong>document.getElement</strong><em><strong>s</strong></em><strong>By*</strong></td><td>looks for elements with the given tag and returns the <strong>collection</strong> of them</td><td><code>document.getElementsByTagName('input')[0].value = 5;</code></td></tr><tr><td><mark style="color:blue;"><strong>Insertion methods</strong></mark></td><td></td><td></td></tr><tr><td><strong>node.append(...nodes or strings)</strong></td><td>append nodes or strings <em>at the end</em> of <code>node</code></td><td></td></tr><tr><td><strong>node.prepend(...nodes or strings)</strong></td><td>insert nodes or strings <em>at the beginning</em> of <code>node</code></td><td></td></tr><tr><td><strong>node.before(...nodes or strings)</strong></td><td>insert nodes or strings <em>before</em> <code>node</code></td><td></td></tr><tr><td><strong>node.after(...nodes or strings)</strong></td><td>insert nodes or strings <em>after</em> <code>node</code></td><td></td></tr><tr><td><strong>node.replaceWith(...nodes or strings)</strong></td><td>replaces <code>node</code> with the given nodes or strings</td><td></td></tr><tr><td><mark style="color:blue;"><strong>Method</strong></mark></td><td></td><td></td></tr><tr><td><strong>elem.matches</strong></td><td>Previous methods were searching the DOM.</td><td><code>document.body.children.matches('a[href$="zip"]'</code></td></tr><tr><td><h4>elem.closest</h4></td><td>looks for the nearest ancestor that matches the CSS-selector.</td><td><code>document.querySelector('.chapter').closest('.contents')); // DIV</code></td></tr><tr><td><mark style="color:blue;"><strong>Change Some content</strong></mark></td><td></td><td></td></tr><tr><td><strong>elem.innerHTML</strong></td><td>allows to get the HTML inside the element as a string.</td><td><code>let name = '&#x3C;b>A&#x3C;/b>';elem.innerHTML = name;</code>  // <strong>A</strong></td></tr><tr><td><strong>elem.textContent</strong></td><td>return pure text inside the element</td><td><code>elem.textContent = name; // &#x3C;b>A&#x3C;/b></code></td></tr><tr><td><mark style="color:blue;"><strong>Styles and classes</strong></mark></td><td></td><td></td></tr><tr><td>elem.className</td><td>replaces the whole string of classes</td><td></td></tr><tr><td>elem.classList</td><td>add/remove a single class</td><td><ul><li><code>elem.classList.add('red')</code></li><li><code>remove('red')</code></li><li><code>toggle('red')</code></li><li><code>contains("class")</code></li></ul></td></tr><tr><td>elem.style.{style}</td><td>an object that corresponds to what’s written in the <code>"style"</code></td><td>elem.style.margin = '20px'</td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td>'</td></tr></tbody></table>

#### Select element

```
<div id="ele">Hi</hi>
<div class="contents">
  <ul class="book">
    <li class="chapter">Chapter 1</li>
    <li class="chapter">Chapter 1</li>
  </ul>
</div>
```

#### **Insert element**

```
<ol id="ol">
  <li>0</li>
  <li>1</li>
  <li>2</li>
</ol>

<script>
  ol.before('before'); // insert string "before" before <ol>
  ol.after('after'); // insert string "after" after <ol>

  let liFirst = document.createElement('li');
  liFirst.innerHTML = 'prepend';
  ol.prepend(liFirst); // insert liFirst at the beginning of <ol>

  let liLast = document.createElement('li');
  liLast.innerHTML = 'append';
  ol.append(liLast); // insert liLast at the end of <ol>
</script>
```

![](https://1787585077-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LqirD3iAZIDk4oDCfwS%2Fuploads%2FkQKiirfUsiMjTyJvf2e7%2FScreen%20Shot%202021-10-22%20at%202.29.33%20PM.png?alt=media\&token=b6bac834-cd5a-47a9-82f8-72b93aea0ed1)

![](https://1787585077-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LqirD3iAZIDk4oDCfwS%2Fuploads%2FmIqEoqqDdid2JJXMI8TV%2FScreen%20Shot%202021-10-22%20at%202.29.36%20PM.png?alt=media\&token=31bbe09d-0032-46b1-943a-0d39defa4b4c)

**Change Some content**

```
<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>
<script>
  let elements = document.querySelectorAll('ul > li:last-child');

  for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
  }
</script>
```

**Styles and classes**

```
<body class="main page">
  <script>
    // add a class
    document.body.classList.add('article');

    alert(document.body.className); // main page article
  </script>
</body>
```

## Attribute

HTML attributes have the following features:

* Their name is case-insensitive (`id` is same as `ID`).
* Their values are always strings, but properties are not always strings. For instance, the `input.checked` property (for checkboxes) is a boolean:

```
<input id="input" type="checkbox" checked> checkbox
<div id="elem" about="Elephant"></div>

 <script>
    alert( elem.getAttribute('About') ); // (1) 'Elephant', reading

    elem.setAttribute('Test', 123); // (2), writing

    alert( elem.outerHTML ); // (3), see if the attribute is in HTML (yes)

    for (let attr of elem.attributes) { // (4) list all
      alert( `${attr.name} = ${attr.value}` );
    }
  </script>
```

* `elem.hasAttribute(name)` – checks for existence.
* `elem.getAttribute(name)` – gets the value.
* `elem.setAttribute(name, value)` – sets the value.
* `elem.removeAttribute(name)` – removes the attribute
* `ele.attributes` - a collection of objects that belong to a built-in [Attr](https://dom.spec.whatwg.org/#attr) class, with `name` and `value` properties.

### dataset

**All attributes starting with “data-” are reserved for programmers’ use. They are available in the `dataset` property.**

```
<div id="userState" data-order-state="new"> </div>
<script> 
    alert(userState.dataset.orderState); // new 
    // modify
    userState.dataset.orderState = "pending"; // (*)
</script>
```

![](https://1787585077-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LqirD3iAZIDk4oDCfwS%2Fuploads%2FezP838UWlmJhT7VJSSE0%2FScreen%20Shot%202021-10-18%20at%2012.02.32%20PM.png?alt=media\&token=120713ec-a859-4dc7-99cb-b0c3105755ab)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hannahpun.gitbook.io/leetcode-note/bi-ji-note/walking-the-dom.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
