简体   繁体   中英

How to remove content within a parent div using javascript?

Within the parent div, I am trying to add/appedn the html content show in the javascript below. I am also trying to remove the existing html, the pre-existing html in the parent div which is the everything that has class like.

Any ideas on how to do this?

<script>
    $(document).ready(function(){
        $('.like').click(function (e) {
            e.preventDefault();
            $(this).parent().append("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");
            // $(this).parent().('.like').empty();

            console.log('liked');
        })
    })
 </script>



                   <div>                  
                    <a href = "#" class = 'like'>
                        <div class = 'coal'></div>
                    </a>
                  </div> 

尝试$(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>");

尝试这个:

$(this).parent().('.like').remove();

Removing previous html

$('.like').click(function () {
  $(this).parent()
  .html('');
  return false;
})

This will remove the HTML codes and the next step will add the html that you want to be added.

Append the code

$('.like').click(function () {
  $(this).parent()
  .append('<a href = '#' class = 'unlike'><div class = 'heart'></div></a>');
  return false;
})

So instead of that try to just replacing the previous code with the newer one.

Replacing the previous html with newer one

This would do the trick

$('.like').click(function () {
  $(this).parent()
  .html('<a href = '#' class = 'unlike'><div class = 'heart'></div></a>');
  return false;
})

What does this code do?

This will first get executed when you click on the element with class like . Then it will go for the parent element, and update its html code; which means everything inside it, to the code that you'll provide inside the brackets. Then the return false is a replacement for e.preventDefault you can use that one if you prefer.

Try this

$(document).ready(function(){
        $('.like').click(function (e) {
            e.preventDefault();

            $(this).parent().append("<a href = '#'   class ='unlike'><div class = 'heart'>unlike</div></a>");

            $(this).parent().find('.like').remove();

           console.log('liked');
        })
    })

Check the working jfiddle

Hoe this helps..

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