JavaScriptチートシート7(DOM操作3:ツイートアプリ)
| 登録日 | :2025/02/09 15:22 |
|---|---|
| カテゴリ | :Linux |
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Form Event</h1>
<form id="tweetForm" action="/hoge">
<input type="text" name="username" placeholder="username">
<input type="text" name="tweet" placeholder="How are you?">
<button>Tweeted</button>
</form>
<h2>Tweeted list</h2>
<ul id="tweets"></ul>
<script src="app7.js"></script>
</body>
</html>
Javascript
const tweetForm = document.querySelector('#tweetForm');
const tweetsContainer = document.querySelector('ul');
tweetForm.addEventListener('submit', (e) => {
e.preventDefault();
const username = tweetForm.elements.username;
const tweet = tweetForm.elements.tweet;
addTweet(username.value, tweet.value);
username.value = '';
tweet.value = '';
});
tweetsContainer.addEventListener('click', (e) => {
// console.log('clikc ul');
// console.log(e);
// //Case1
// if(e.target.nodeName === 'LI'){
// e.target.remove()
// }else{
// e.target.parentElement.remove()
// }
// //Case2
// e.target.nodeName === 'LI' && e.target.remove();
// e.target.nodeName === 'B' && e.target.parentElement.remove();
//Case3->wrong
if (e.target.nodeName === 'LI' || e.target.nodeName === 'B'){
e.target.closest('LI').remove();
}
})
const addTweet = (username, tweet) => {
const newTweet = document.createElement('li');
const bTag = document.createElement('b');
bTag.append(username);
newTweet.append(bTag);
newTweet.append(` - ${tweet}`);
tweetsContainer.append(newTweet);
}