简体   繁体   中英

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. So I'd like to ask how should my destroy.js.erb looks like?

<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:

<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:

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

Result in DOM:

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

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

Use JQuery .remove

example form jquery reference

html page

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

javascript jquery (remove the element wiht the class "hello"

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

result ind DOM

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

With JavaScript Using remove()

Answer:1

You can remove elements like this:

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

Answer:2 Source

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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