Skip to content
Advertisement

Remove parent and child elements on span click with plain javascript

I am replacing a piece of jQuery with plan javascript. I have managed to replace some of it, but I am struggling with a dynamically added element, which should have some sort of on click handler that removes it’s parent and the parents children.

Intial piece of PHP code retrives the stored data and displays it.

if(count( $coordinates ) > 0 ) {
     if(!empty($coordinates)){
          foreach( $coordinates as $coords ) {
              foreach( $coords as $coord ) {
                printf( 
                 '<p>
                    Coordinate: <input type="text" name="coordinatesId[%1$s][title]" value="%2$s" /> 
                    Latitude & Longitude: <input type="text" name="coordinatesId[%1$s][coord]" value="%3$s" /
                    <span id="spanRmv" class="remove">%4$s</span>
                 </p>', 
                $c, 
                $coord['title'],   
                $coord['coord'], 
                __( ' Remove' ) );
                
                $c++;
             }
         }
     }
 }

 <span id="here"></span>

 <span id="spanBtn">
    <?php _e('Add new field'); ?>
 </span>    
 

It should be possible to add new fields using an onclick event. That it is currently managed by jQuery, but to be replaced by Javascript.

var $ = jQuery.noConflict();
        
$(document).ready(function() {
        
    var count = <?php echo $c; ?>;
            
    $(".add").click(function() {
                
        count = count + 1;

        $('#here').append('<p>Coordinate: <input type="text" name="coordinatesId['+count+'][title]" value="" /> Latitude & Longitude: <input type="text" name="coordinatesId['+count+'][coord]" value="" /><span id="spanRmv" class="remove"> Remove</span></p>' );
                
        return false;
    });
    $(".remove").live('click', function() {
        $(this).parent().remove();
    });
});

I managed to replace the jQuery element with Javascript, which adds a new element.

var count = <?php echo $c; ?>;
let spanBtn = document.getElementById('spanBtn');

spanBtn.onclick = function() {
                
    count = count + 1;

    console.log("Adding additional field number " + count);

    document.getElementById("here").innerHTML +=  
        '<p>Coordinate: <input type="text" name="coordinatesId['+count+'][title]" value="" /> Latitude & Longitude: <input type="text" name="coordinatesId['+count+'][coord]" value="" /><span id="spanRmv" class="remove"> Remove</span></p>';

    return false;

}

I am however not able to replace the piece of jQuery which removes the parent and it’s children on click event. One part of the challenge is that the element is dynamic and added after DOM finished loading. This my current failing attempt:

let spanRmv = document.getElementById('spanRmv');

document.addEventListener('click', function(e){
    if(e.target && e.target.id=='spanRmv'){
            
        console.log("Removing existing field!");
                
                    
        e.parentNode(e.parentNode.parentNode);
    }
})

This resolves in following error ‘Uncaught TypeError: Cannot read property ‘parentNode’ of undefined’ on click.

Can anyone suggest me on how to deal with this onclick event to remove parent with children of this dynamic content?

Advertisement

Answer

Thank you, mplungjan. Your answer helped me in the right direction.

Following is the code I ended up with which both neabled me to remove elements once applied and also while clicking ‘remove’ of elements that is not yet saved.

if(count( $coordinates ) > 0 ) {
   if(!empty($coordinates)){
       foreach( $coordinates as $coords ) {
          foreach( $coords as $coord ) {
            printf( 
                '<div>
                    Coordinate: <input type="text" name="coordinatesId[%1$s][title]" value="%2$s" /> 
                    Latitude & Longitude: <input type="text" name="coordinatesId[%1$s][coord]" value="%3$s" />
                        <button type="button" class="remove">%4$s</button></p>
                    </div>', 
                    $c, 
                    $coord['title'],   
                    $coord['coord'], 
                    __( ' Remove' ) );
                $c++;
            }
        }
    }    
}

?>
    
<span id="here"></span>

<button type="button" id="btn">Add new field</button>

Following is the Javascript which replaced jQuery.

<script>
        document.addEventListener('DOMContentLoaded', function() {
            
            console.log('DOM is ready!');

            const btn = document.getElementsByClassName('remove')

            for (var i = 0; i < btn.length; i++) {
                btn[i].addEventListener('click', function(e) {
                    
                    console.log("Removing existing field!");

                    e.currentTarget.parentNode.remove();

                }, false);
            }
        });

        window.addEventListener('load', function() {
            
            const here = document.getElementById('here'); 

            here.addEventListener('click', function(e) {
                const tgt = e.target;
                
                if (tgt.classList.contains('remove')) {
                    console.log("Removing existing field!");
                    
                    tgt.closest('div').remove();
                }

            });

            var count = <?php echo $c; ?>;

            document.getElementById('btn').addEventListener('click', function() {

                count = count + 1;

                console.log("Adding additional field number " + count + "!");

                here.innerHTML += `<div>Coordinate: <input type="text" name="coordinatesId[${count}][title]" value="" /> 
                    Latitude & Longitude: <input type="text" name="coordinatesId[${count}][coord]" value="" />
                    <button type="button" class="remove"> Remove</button></div>`;
            });
        });
    </script>

Thanks!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement