简体   繁体   中英

How can I remove p tag if it contains less than 4 characters?

I'm struggling with removing a paragraph tag whenever it doesn't have content. It gets the content dynamically, but sometimes there's no content for the element, so it get's really ugly. How can I remove the paragraph whenever this happens?

// try 1
if ($('.package-codes').length < 4) {
    $(this).remove();
}

// try 2
$('.code').filter(function() {
    return $(this).text().length < 5 ;
});

Here's an codepen of my markup. http://codepen.io/michaelwilhelmsen/pen/XbwNaW

EDIT:

After looking at your replies I've realized that the content get's added by ajax, and for some reason the .remove method doesn't get applied to the elements. Could it be because the functions are put in effect before the markup is there?

Try to invoke .remove() over the filtered elements,

$('.code').filter(function() {
  return $(this).text().length < 5 ;
}).remove();

DEMO

add remove method after filter, check here

$('.code').filter(function() {
  return $(this).text().length < 5 ;
}).remove();

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