【问题标题】:How can I remove/delete a HTML element using JavaScript?如何使用 JavaScript 移除/删除 HTML 元素?
【发布时间】:2022-02-08 09:35:02
【问题描述】:

我正在创建一个警告段落,如果电子邮件不正确、为空或已发送,则会显示错误。发生的情况是,在显示第一个警告后,我想取消另一个警告的创建,这样就不会堆积起来。

我正在尝试的当前选项是如果警告已经存在则删除它,否则可以创建它。但我不知道为什么它没有发生。

JS:

const input = document.querySelector('#emailInput');
const form = document.querySelector('#myForm')
const button = document.querySelector('#notify')
const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

form.addEventListener('submit', function (e){
    e.preventDefault()
});

button.addEventListener('click', validateEmail)

function validateEmail(){
    let inputValue = input.value;
    if(inputValue.match(validRegex)){
        createWarning('Email sent!')
    }
    else if(inputValue == ''){
        createWarning('Please provide an email!');
    }
    else{
        createWarning('Please provid a valid email address')
    }
}

function createWarning(message){
    let warning = document.createElement('p');
    if (document.getElementById(warning) == null){
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }
    
    else{
        const error = getElementById(warning)
        error.remove()
    }
    
}
@import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');

*{
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

body{
    background-color: whitesmoke;
    font-size: 20px;
    font-family: 'Libre Franklin', sans-serif;
    display: flex;
    flex-direction: column;
    align-content: space-between;
    height: 100vh;
}

.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    height: 100%;
}

.title{
    display: flex;
    align-items: center;
    justify-content: center;
}

.company-name{
    font-family: 'Libre Franklin', sans-serif;
    font-weight: 700;
    font-size: 20px;
}

.dot{
    color: hsl(223, 87%, 63%);
}

.intro{
    display: flex;
    flex-direction: column;
    align-items: center;
    align-content: space-between;
    gap: 15px;
    justify-content: space-between;
}

.subtitle h2{
    font-weight: 600;
    font-size: 20px;
}

.launching{
    color: rgba(190, 160, 83, 0.602);
    font-weight: 200;
}

.paragraph p{
    font-weight: 300;
    font-size: 14px;
    color: rgb(41, 37, 0);
}

form{
    display: flex;
    align-items: center;
    align-content: space-between;
    flex-direction: column;
}

#emailInput{
    border-radius: 50px;
    border: 1px solid hsl(223, 100%, 88%);
    width: 100%;
    padding: 10px 35px;
    font-family: 'Libre Franklin', sans-serif;
}

.warning{
    color: hsl(354, 100%, 66%);
    font-size: small;
    font-family: 'Libre Franklin', sans-serif;
    margin: 5px;
}

#emailInput:focus{
    outline: none;
}

#notify{
    background-color: hsl(223, 87%, 63%);
    color: whitesmoke;
    border-radius: 50px;
    padding: 10px 20px;
    width: 100%;
    border: 1px solid rgba(88, 78, 78, 0);
    font-weight: bold;
    margin-top: 15px;
}

.social-media{
    width: 200px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    align-content: space-between;
    justify-items: center;
}

.around{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    border: 1px solid hsla(0, 0%, 59%, 0.192);
    border-radius: 50%;
    width: 30px;
    height: 30px;
}
.fab{
    color: hsl(223, 87%, 63%);
    font-size: medium;
}

.attribution { font-size: 11px; text-align: center; }
.attribution a { color: hsl(228, 45%, 44%); }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->

  <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
  <link rel="stylesheet" href="style.css">
  <script src="https://kit.fontawesome.com/b5c693247f.js" crossorigin="anonymous"></script>
  <title>Frontend Mentor | Ping coming soon page</title>
</head>
<body>
  <div class="container">
    <div class="title">
      <h1 class="company-name">PING<span class="dot">.</span></h1>
    </div>
    <div class="intro">
      <div class="subtitle"><h2><span class="launching">We are launching</span> soon!</h2></div>
      <div class="paragraph"><p>Subscribe and get notified</p></div>
      <div class="form-container">
        <form id="myForm" name="myForm">
          <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
          <button type="submit" id="notify">Notify Me</button>
        </form>
      </div>
    </div>
    <div class="img-container">
      <img src="images/illustration-dashboard.png" alt="Dashboard Image" width="300" height="250">
    </div>
    <div class="social-media">
      <div class="around"><i class="fab fa-facebook-f"></i></div>
      <div class="around"><i class="fab fa-twitter"></i></div>
      <div class="around"><i class="fab fa-instagram"></i></div>
    </div>
  </div>

  <footer>
    <p class="attribution">
      Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. 
      Coded by <a href="https://github.com/HBortolim">Henrique Bortolim</a>.
    </p>
  </footer>
  <script src="app.js"></script>
</body>
</html>

【问题讨论】:

    标签: javascript function dom dom-manipulation


    【解决方案1】:

    您将 字符串标识符 'warning'warning 变量混淆了:

    let warning = document.createElement('p');
    

    这是将变量warning 设置为段落元素。

    if (document.getElementById(warning) == null){
    

    在这里,您将warning 变量 传递给getElementById,它被设置为HTML 元素,所以它永远不会找到它。 p>

    const error = getElementById(warning)
    error.remove()
    

    你又犯了同样的错误。

    稍作调整,效果会更好:

    function createWarning(message){
        const existingWarning = document.getElementById('warning');
        if (existingWarning) {
          existingWarning.remove();
        }
    
        const warning = document.createElement('p');
        warning.innerHTML = message;
        warning.classList.add('warning');
        warning.setAttribute('id','warning');
        input.insertAdjacentElement('afterend',warning);
    }
    

    【讨论】:

    • 感谢您的解决方案并解释我的错误,现在我明白了,祝您有美好的一天!
    【解决方案2】:

    document 调用getElementById 并使用基于字符串的ID 进行“警告”而不是引用元素作为document.getElementById() 的参数更正的代码如下:

    const input = document.querySelector('#emailInput');
    const form = document.querySelector('#myForm')
    const button = document.querySelector('#notify')
    const validRegex = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    
    form.addEventListener('submit', function (e){
        e.preventDefault()
    });
    
    button.addEventListener('click', validateEmail)
    
    function validateEmail(){
        let inputValue = input.value;
        if(inputValue.match(validRegex)){
            createWarning('Email sent!')
        }
        else if(inputValue == ''){
            createWarning('Please provide an email!');
        }
        else{
            createWarning('Please provid a valid email address')
        }
    }
    
    function createWarning(message){
        let warning = document.createElement('p');
        let warningId = 'warning';
        if (document.getElementById(warningId) == null) {
            warning.innerHTML = message;
            warning.classList.add('warning');
            warning.setAttribute('id', warningId);
            input.insertAdjacentElement('afterend',warning);
        }    
        else {
            const error = document.getElementById(warningId)
            error.remove()
        }    
    }
    @import url('https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;600;700&display=swap');
    
    *{
         margin: 0;
         padding: 0;
         box-sizing: border-box;
    }
    
    body{
        background-color: whitesmoke;
        font-size: 20px;
        font-family: 'Libre Franklin', sans-serif;
        display: flex;
        flex-direction: column;
        align-content: space-between;
        height: 100vh;
    }
    
    .container{
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-evenly;
        height: 100%;
    }
    
    .title{
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .company-name{
        font-family: 'Libre Franklin', sans-serif;
        font-weight: 700;
        font-size: 20px;
    }
    
    .dot{
        color: hsl(223, 87%, 63%);
    }
    
    .intro{
        display: flex;
        flex-direction: column;
        align-items: center;
        align-content: space-between;
        gap: 15px;
        justify-content: space-between;
    }
    
    .subtitle h2{
        font-weight: 600;
        font-size: 20px;
    }
    
    .launching{
        color: rgba(190, 160, 83, 0.602);
        font-weight: 200;
    }
    
    .paragraph p{
        font-weight: 300;
        font-size: 14px;
        color: rgb(41, 37, 0);
    }
    
    form{
        display: flex;
        align-items: center;
        align-content: space-between;
        flex-direction: column;
    }
    
    #emailInput{
        border-radius: 50px;
        border: 1px solid hsl(223, 100%, 88%);
        width: 100%;
        padding: 10px 35px;
        font-family: 'Libre Franklin', sans-serif;
    }
    
    .warning{
        color: hsl(354, 100%, 66%);
        font-size: small;
        font-family: 'Libre Franklin', sans-serif;
        margin: 5px;
    }
    
    #emailInput:focus{
        outline: none;
    }
    
    #notify{
        background-color: hsl(223, 87%, 63%);
        color: whitesmoke;
        border-radius: 50px;
        padding: 10px 20px;
        width: 100%;
        border: 1px solid rgba(88, 78, 78, 0);
        font-weight: bold;
        margin-top: 15px;
    }
    
    .social-media{
        width: 200px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        align-content: space-between;
        justify-items: center;
    }
    
    .around{
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        border: 1px solid hsla(0, 0%, 59%, 0.192);
        border-radius: 50%;
        width: 30px;
        height: 30px;
    }
    .fab{
        color: hsl(223, 87%, 63%);
        font-size: medium;
    }
    
    .attribution { font-size: 11px; text-align: center; }
    .attribution a { color: hsl(228, 45%, 44%); }
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
    
      <link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
      <link rel="stylesheet" href="style.css">
      <script src="https://kit.fontawesome.com/b5c693247f.js" crossorigin="anonymous"></script>
      <title>Frontend Mentor | Ping coming soon page</title>
    </head>
    <body>
      <div class="container">
        <div class="title">
          <h1 class="company-name">PING<span class="dot">.</span></h1>
        </div>
        <div class="intro">
          <div class="subtitle"><h2><span class="launching">We are launching</span> soon!</h2></div>
          <div class="paragraph"><p>Subscribe and get notified</p></div>
          <div class="form-container">
            <form id="myForm" name="myForm">
              <input type="email" id="emailInput" name="emailInput" placeholder="Your email address...">
              <button type="submit" id="notify">Notify Me</button>
            </form>
          </div>
        </div>
        <div class="img-container">
          <img src="images/illustration-dashboard.png" alt="Dashboard Image" width="300" height="250">
        </div>
        <div class="social-media">
          <div class="around"><i class="fab fa-facebook-f"></i></div>
          <div class="around"><i class="fab fa-twitter"></i></div>
          <div class="around"><i class="fab fa-instagram"></i></div>
        </div>
      </div>
    
      <footer>
        <p class="attribution">
          Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>. 
          Coded by <a href="https://github.com/HBortolim">Henrique Bortolim</a>.
        </p>
      </footer>
      <script src="app.js"></script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 2016-05-17
      • 2015-10-26
      • 2021-07-29
      • 1970-01-01
      • 2020-03-22
      • 2019-06-27
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多