Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaScript DOM to make a simple message board

Shulou Source: shulou.com Published: 2022-06-01 06:09:34 11月07日 Update

This article mainly introduces the relevant knowledge of "how to use JavaScript DOM to make a simple message board". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use JavaScript DOM to make a simple message board" can help you solve the problem.

Prepare the html code first:

Publish

The css code is as follows:

* {

Margin: 0

Padding: 0

}

Body {

Padding: 100px

}

Textarea {

Width: 200px

Height: 100px

Border: 1px solid pink

Outline: none

Resize: none

}

Ul {

Margin-top: 50px

}

Li {

Width: 300px

Padding: 5px

Background-color: rgb (245,209,243)

Color: red

Font-size: 14px

Margin: 15px 0

}

Next is the most important part, we first use document.querySelector () to get the objects we want to operate on: button,textarea and ul

Then register the click event to button, add in the middle to determine whether there is input, if there is input, then continue the operation, use document.createElement ('li') to create a li tag, then use Li [XSS _ clean] to get the value entered by the textarea control user, and finally use ul.insertBefore (li,ul.children [0]) to insert the created li tag.

Note: because the message board displays the latest messages, it is inserted at the front of the li.

The complete code is as follows:

Publish

/ / get the element

Var btn = document.querySelector ('button')

Var text = document.querySelector ('textarea')

Var ul = document.querySelector ('ul')

/ / Registration event

Btn.onclick = function () {

If (text.value = ='') {

Alert ('you didn't lose content')

Return false

} else {

Var li = document.createElement ('li')

Li [XSS _ clean] = text.value

Ul.insertBefore (li, ul.children [0])

}

Text.value =''

}

This is the end of the introduction to "how to make a simple message board using JavaScript DOM". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Message boards content production code knowledge input events tags industries different practical important next elements practicality actual objects controls articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information MySQL vpn Shulou Technology Xiaomi