---
title: Parser HTML
project: Total.js V4
version: 0.0.99
section: reference
language: it
license: MIT
url: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/html-parser/
updated: 2026-11-18T16:57:49.579Z
---

# Parser HTML

> String.parseHTML(), HTMLElement e i metodi di un nodo.

## API

### String.parseHTML([trim])

Type: `method`

Interpreta una stringa HTML in un albero di nodi `HTMLElement`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `trim` | `Boolean` | no | `false` | Elimina gli spazi dai nodi di testo e salta quelli vuoti. |

Returns: `HTMLElement` L'elemento radice.

Restituisce un elemento radice senza nome di tag; i suoi `children` sono i nodi di primo livello. I commenti, `<!DOCTYPE>` e le dichiarazioni `<?xml ?>` vengono ignorati. Un tag di chiusura mancante si chiude alla fine dell'input. I tag void (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) non hanno figli.

Example: Trovare tutti i link
```js
var dom = html.parseHTML(true);
var links = dom.find('a');
for (var a of links)
	console.log(a.attr('href'), a.text());
```

### HTMLElement

Type: `class`

Un nodo di un albero HTML interpretato.

Proprietà: `tagName` (in maiuscolo, `TEXT` per i nodi di testo), `raw` (il nome del tag come è scritto), `attrs` (un oggetto di attributi), `children`, `parentNode`, `textContent` (solo nodi di testo), `unpair` (`true` per i tag void), `innerHTML` e `innerText` (getter). Un tag con un namespace (`<g:item>`) ha anche `prefix` (`G:`). Tutti i metodi che modificano restituiscono l'elemento, così puoi concatenarli.

Example: Leggere e modificare un nodo
```js
var dom = '<div class="box"><p data-id="1">Hello</p></div>'.parseHTML();
var p = dom.find('p')[0];
console.log(p.tagName, p.attrs, p.parentNode.tagName);
// P { 'data-id': '1' } DIV
```

### node.find(selector)

Type: `method`

Trova gli elementi discendenti che corrispondono a un selettore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes |  | Il selettore. |

Returns: `Array` Gli elementi corrispondenti.

Selettori supportati: un nome di tag (`div`), `*`, `#id`, `.class`, il valore di un attributo (`[name="value"]`), un discendente (`div p`) e un figlio diretto (`div > p`). Separa più selettori con una virgola. Un prefisso di namespace che termina con due punti (`g:`) corrisponde a tutti i tag di quel namespace. Il risultato è un array con i metodi aggiuntivi di [elements.html()](#elements-html).

Example: Selettori
```js
var dom = html.parseHTML();
var images = dom.find('img[alt="Logo"]');
var items = dom.find('ul.menu > li');
var both = dom.find('h1, h2');
```

### node.closest(selector)

Type: `method`

Trova gli antenati che corrispondono a un selettore.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `selector` | `String` | yes |  | Il selettore. |

Returns: `Array` Gli antenati corrispondenti.

Cerca dal genitore fino alla radice.

Example: Trovare il form genitore
```js
var form = input.closest('form')[0];
```

### node.parent()

Type: `method`

Restituisce l'elemento genitore.

Returns: `HTMLElement`

Uguale a `node.parentNode`.

Example: Genitore
```js
var li = dom.find('a')[0].parent();
```

### node.browse(fn, [reverse])

Type: `method`

Percorre tutti gli elementi discendenti.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(node)` | yes |  | Chiamata per ogni elemento. |
| `reverse` | `Boolean` | no | `false` | Percorre invece gli antenati. |

Returns: `HTMLElement` L'elemento stesso.

La funzione viene chiamata per ogni elemento (i nodi di testo vengono saltati). Restituisci `true` per saltare i figli di quell'elemento. Con `reverse` risale attraverso gli antenati.

Example: Contare gli elementi
```js
var count = 0;
dom.browse(function(node) {
	count++;
});
```

### node.attr(name, [value])

Type: `method`

Legge o imposta un attributo.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome dell'attributo. |
| `value` | `String` | no |  | Il nuovo valore. |

Returns: `String|HTMLElement` Il valore in lettura, altrimenti l'elemento.

Senza `value` restituisce l'attributo. `null` o una stringa vuota rimuovono l'attributo; qualsiasi altro valore viene memorizzato come stringa.

Example: Impostare alt
```js
dom.find('img')[0].attr('alt', 'Logo');
```

### node.attrd(name, [value])

Type: `method`

Legge o imposta un attributo `data-`.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | Il nome senza `data-`. |
| `value` | `String` | no |  | Il nuovo valore. |

Returns: `String|HTMLElement`

Uguale a `node.attr('data-' + name, value)`.

Example: Leggere data-id
```js
var id = node.attrd('id');
```

### node.aclass(cls)

Type: `method`

Aggiunge classi CSS.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cls` | `String` | yes |  | I nomi delle classi. |

Returns: `HTMLElement`

Più classi possono essere separate da uno spazio o da una virgola.

Example: Aggiungere classi
```js
node.aclass('active highlighted');
```

### node.rclass(cls)

Type: `method`

Rimuove classi CSS.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cls` | `String` | yes |  | I nomi delle classi. |

Returns: `HTMLElement`

Più classi possono essere separate da uno spazio o da una virgola.

Example: Rimuovere una classe
```js
node.rclass('hidden');
```

### node.tclass(cls, [value])

Type: `method`

Alterna classi CSS.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cls` | `String` | yes |  | I nomi delle classi. |
| `value` | `Boolean` | no |  | Forza l'aggiunta o la rimozione. |

Returns: `HTMLElement`

Senza `value` aggiunge le classi mancanti e rimuove quelle presenti. Con `value` aggiunge le classi quando `value` è truthy e le rimuove quando è falsy.

Example: Alternare in base a una condizione
```js
node.tclass('selected', item.id === current);
```

### node.hclass(cls)

Type: `method`

Controlla una classe CSS.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `cls` | `String` | yes |  | Un nome di classe. |

Returns: `Boolean`

Restituisce `true` quando l'elemento ha la classe.

Example: Controllo
```js
if (node.hclass('external'))
	node.attr('target', '_blank');
```

### node.css(key, [value])

Type: `method`

Imposta gli stili inline.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `key` | `String|Object` | yes |  | La proprietà, oppure un oggetto `{ property: value }`. |
| `value` | `String` | no |  | Il valore. |

Returns: `HTMLElement`

Accetta una proprietà e un valore, oppure un oggetto di proprietà. Un valore vuoto rimuove la proprietà. Il risultato viene scritto nell'attributo `style`.

Example: Stili
```js
node.css('color', 'red');
node.css({ 'font-weight': 'bold', color: '' });
```

### node.remove()

Type: `method`

Rimuove l'elemento dal suo genitore.

Returns: `HTMLElement` L'elemento rimosso.

Example: Rimuovere tutti gli script
```js
for (var script of dom.find('script'))
	script.remove();
```

### node.append(html)

Type: `method`

Interpreta HTML e lo aggiunge alla fine dei figli.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `html` | `String` | yes |  | L'HTML da aggiungere. |

Returns: `HTMLElement|Array`

Restituisce il nuovo elemento, oppure un array quando l'HTML ha più nodi di primo livello.

Example: Append
```js
var li = dom.find('ul')[0].append('<li>New</li>');
```

### node.prepend(html)

Type: `method`

Interpreta HTML e lo aggiunge all'inizio dei figli.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `html` | `String` | yes |  | L'HTML da aggiungere. |

Returns: `HTMLElement`

Restituisce la radice dell'HTML interpretato (non il nuovo elemento).

Example: Prepend
```js
dom.find('body')[0].prepend('<header>Top</header>');
```

### node.text()

Type: `method`

Restituisce il testo dell'elemento senza tag.

Returns: `String`

Le entità HTML vengono decodificate (`&amp;` diventa `&`). `node.innerText` restituisce il testo senza decodifica.

Example: Leggere il testo
```js
'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();
// A & B
```

### node.html([formatted])

Type: `method`

Serializza di nuovo l'elemento in HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `formatted` | `Boolean` | no | `false` | Indenta l'output. |

Returns: `String`

Per la radice serializza i figli. `formatted` mette ogni nodo su una riga propria con indentazione a tabulazioni. `node.toString()` è lo stesso metodo. Gli attributi `class`, `id` e `data-` vuoti vengono esclusi.

Example: Modificare e salvare
```js
var dom = html.parseHTML();
dom.find('img').attr('loading', 'lazy');
var output = dom.html();
```

### elements.html([formatted])

Type: `method` · Since: `0.0.98`

Serializza tutti gli elementi trovati in un'unica stringa HTML.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `formatted` | `Boolean` | no | `false` | Mette ogni elemento su una riga propria. |

Returns: `String`

L'array restituito da `find()` e `closest()` ha anche `aclass()`, `rclass()`, `tclass()`, `attr()` e `attrd()`, che si applicano a ogni elemento e restituiscono l'array. `toString()` è un alias di `html()`.

Example: Lavorare con tutti i risultati
```js
var items = dom.find('li');
items.aclass('item').attrd('ready', '1');
console.log(items.html());
```
