DEV Community

Cover image for จัดการ DOM ด้วย bind:this และใช้งาน DOM
thinny
thinny

Posted on

จัดการ DOM ด้วย bind:this และใช้งาน DOM

ในสมัยก่อนยุคของ AJAX ปัญหาอย่างหนึ่งในการสร้างเว้บด้วยภาษา javascript ก้คือการ จัดการกับ Document Object Model(DOM) การใช้ Javascript ไป maintain DOM ทำได้ยากมาก พอมายุคที่มี jquery การเขียนคสบคุม DOM เริ่มง่ายขึ้น

เริ้มจากสร้าง HTML ง่ายๆก่อน และใช้งาน bind:this={ตัวแปร type HTMLElemnt}

<!-- HTML -->
<div bind:this={Div}></div>
Enter fullscreen mode Exit fullscreen mode

ต่อมาผูกตัวแปร Div โดย type เป็น HTMLElement

let Div;

// Typescript
let Div: HTMLElement;
Enter fullscreen mode Exit fullscreen mode

modify DOM ด้วย vanilaJS

<script>
import {onMount} from 'svelte';
let Div;

onMount(() => {
    Div.textContent = 'Text Content'
    Div.style.color= 'red'
    Div.style.fontSize='24px'
    Div.style.backgroundColor ='#f4fcfc'
    Div.style.padding = '20px'
})

</script>
Enter fullscreen mode Exit fullscreen mode

ผลลัพธ์
Alt Text

ดูตัวอย่างได้ที่ REPL

หากสนใจ svelte สามารถเรียนรู้การใช้งาน svelte แบบ step by step ได้ที่
Svelte: Framework Not Framework — (ตอนที่ 1) แรกรู้จัก

ขอบคุณทุกท่านที่อ่านมาถึงตรงนี้ ถ้าอ่านแล้วรู้มีประโยชน์ ฝากกด Subscribe หรือ share link ให้คนอื่นรับรู้ด้วยนะครับ ขอบคุณครับ

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay