简体   繁体   English

如何从js中的div中删除元素?

[英]How to remove element from div in js?

I have list of descriptions and after remove one of them, I'd like to remove that element from div (one element from list of descriptions), not refreshing site. 我有描述列表,删除其中一个后,我想从div中删除该元素(描述列表中的一个元素),而不是刷新站点。 So I'd like to ask how should my destroy.js.erb looks like? 所以我想问一下我的destroy.js.erb应该是什么样子?

<div class="container">
        <div class="box">
                 <div class="descriptions">
                      <%= render @descriptions %> 
                  </div>
        </div>
</div>

//_description.html.erb
<div class="description-field">
  <%= @description.text %>
</div>

Assuming you're using jQuery because you are using Rails, you could potentially do something like this: 假设由于使用Rails而使用jQuery,则可能会执行以下操作:

<div class="container">
  <div class="box">
    <div class="descriptions">
      <p class="remove-descriptions">
        <%= render @descriptions %>
      </p> 
    </div>
  </div>
</div>

//_description.html.erb
<div class="description-field">
  <p class="remove-descriptions">
    <%= @description.text %>
  </p>
</div>

You could then use jQuery to remove that element from <div class="descriptions"> with the following: 然后,您可以使用jQuery使用以下命令从<div class="descriptions">删除该元素:

$('.remove-descriptions').remove();

Result in DOM: 结果在DOM中:

<div class="container">
  <div class="box">
    <div class="descriptions">           
    </div>
  </div>
</div>

//_description.html.erb
<div class="description-field">      
</div>

Use JQuery .remove 使用JQuery .remove

example form jquery reference 示例表单jQuery参考

html page HTML页面

<div class="container">
   <div class="hello">Hello</div>
   <div class="goodbye">Goodbye</div>
</div>

javascript jquery (remove the element wiht the class "hello" javascript jquery(删除带有“ hello”类的元素

 $( ".hello" ).remove();

result ind DOM 结果ind DOM

<div class="container">
  <div class="goodbye">Goodbye</div>
</div>

With JavaScript Using remove() 使用JavaScript使用remove()

Answer:1 答:1

You can remove elements like this: 您可以删除以下元素:

document.getElementById("my-element").remove();

Answer:2 Source 答案:2 来源

HTML: HTML:

<div id="div-01">Here is div-01</div>
<div id="div-02">Here is div-02</div>
<div id="div-03">Here is div-03</div>

JS: JS:

var el = document.getElementById('div-01');
el.nextElementSibling.remove(); // Removes the div with the 'div-02' id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM