# グローバルヘルパー

このページでは、QuickUI の読み込み時にグローバルオブジェクトへ登録される 2 つの DOM ヘルパー、`_` と `$` を説明します。

## `$(selector)`

単一の要素 `HTMLElement | null` を返します。

```demo
<div id="app" class="card">
  <input name="email" />
  <button>Send</button>
</div>

<script>
  console.log($("#app").id);
  console.log($("app").id);
  console.log($(".card").className);
  console.log($("input[name=email]").name);
  console.log($("button").textContent);
</script>
```

| 入力 | 検索方法 |
|---|---|
| `#` で始まる | `#` を取り除いて `getElementById` |
| `.`、`[`、`]` を含む | `querySelector` |
| それ以外 | まず `getElementById`、次に `querySelector` |

返されるのは最初に一致した要素だけです。複数必要な場合は `document.querySelectorAll` を使ってください。

## `_(selector, attributes?, children?)`

CSS セレクター構文から要素を作成します。

```demo
<script>
  const card = _("div#card.box.shadow", { title: "Card", color: "red" }, [
    _("h2", "Title"),
    "plain text",
  ]);
  const img = _("img", "/logo.png");
  const text = _("temp", "text only");
  document.body.append(card);
  console.log(card.outerHTML);
  console.log(img.outerHTML);
  console.log(text.textContent);
</script>
```

| 引数 | 説明 |
|---|---|
| `selector` | `tag#id.class`。タグで始まる必要があり、そうでなければ `undefined` が返ります。タグ名の `-` は保持されるため、`my-card` や `temp-svg` などのカスタム要素も使えます。`temp` は `DocumentFragment` を作成します |
| `attributes` | オブジェクト。下の表を参照してください |
| `children` | 文字列、数値、または配列。引数が 1 つだけの場合、文字列 / 数値 / 配列は `children`、オブジェクトは `attributes` として扱われます |

| `attributes` のキー | 書き込み先 |
|---|---|
| `value`、`innerText`、`innerHTML`、`textContent`、`contentEditable` | 要素のプロパティ |
| `color`、`backgroundColor`、`width`、`height`、`display`、`float` | `style` |
| それ以外 | `setAttribute`。値が `null` または `undefined` の場合はスキップされます |

| `children` の型 | 結果 |
|---|---|
| 文字列または数値 | `innerHTML` に書き込まれます。`img` と `source` では代わりに `src` が設定され、`temp` ではテキストノードが作成されます |
| 配列 | 順に追加されます。文字列と数値はテキストノードになり、`Node`（要素、テキストノード、`DocumentFragment` など）はそのまま追加され、それ以外はスキップされます |

文字列の `children` は `innerHTML` で書き込まれるため、エスケープしていないユーザー入力は絶対に渡さないでください。

---

> [!IMPORTANT]
> **AI エージェント向け：** QuickUI のコードを生成・編集する前に、[QuickUI 生成ガイド](https://quickui.pardn.io/llm_generate_guide.md)（Markdown）を読んでください。サポートされているテンプレート構文と、レンダリングを壊す典型的な誤りがまとめられています。

