How to check if an HTML element contains before deleting it? JQuery

in the function, I need to check if the element (div, span, p) contains any .html elements before trying to remove the html and add new content.

I don’t know how to do it ...

I tried this but did not work:

// HERE below I tried to do a check to see if the div have HTML, but did not work if ($('.'+rowName+' div').html) { $('.'+rowName+' div').html.remove(); $('.'+rowName+' span').html.remove(); $('.'+rowName+' p').html.remove(); } 

Full function

 // Create the Role / Fan rows function rowMaker (rowName, roleName) { //alert(rowName+' '+roleName); // HERE below I tried to do a check to see if the div have HTML, but did not work if ($('.'+rowName+' div').html) { $('.'+rowName+' div').html.remove(); $('.'+rowName+' span').html.remove(); $('.'+rowName+' p').html.remove(); } // Blue button $('.'+rowName+' div').append(roleName); $('.'+rowName+' div').attr('id', 'blue-fan-'+roleName); var blueButton = ('blue-fan-'+roleName); console.log('blueButton = '+blueButton); // Genres $('.'+rowName+' span').append(roleType); // Tags $.each(role_Actor, function(index, item) { $('.'+rowName+' p').append(item+', '); }); $('#'+blueButton).click(function () { console.log('clicked blue button'); // clears the role_Actor to be used to recapture checkboxes role_Actor = []; console.log('role_Actor = '+role_Actor); //$('#modal-'+roleId).modal(); $('#modal-'+roleId).modal({persist:true}); return false; }); } 
+8
javascript jquery html remove-if
source share
5 answers

html is not a property, you need to use () , then you can use the length property of the String object to check the length of the returned html string:

 if ( $.trim( $('.'+rowName+' div').html() ).length ) { // $('.'+rowName).find('div, p, span').remove(); $('.'+rowName).find('div, p, span').empty(); } 

Please note that if you want to change the content of an HTML element, there is no need to remove the current html content from it. html method overrides the current html content.

+12
source share

Check the length of the children.

 if($('.'+rowName+' div').children().length > 0) 
+5
source share

You can use .html() for this (and consider spaces):

 var $row = $('.rowName'); if (!$row.find('div').html().trim().length) { $row.find('div, span, p').empty(); } 
+2
source share

Try

 if ($('.'+rowName+' div').html().length > 0) { $('.'+rowName+' div').empty(); $('.'+rowName+' span').empty(); $('.'+rowName+' p').empty(); } 
+1
source share

Normal vanilla JavaScript should do the trick too.

 if(document.querySelectorAll('.'+rowName+' div')[0].childElementCount > 0){ console.log("found"); } 
0
source share

All Articles