Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Saturday, January 30, 2016

jQuery .closest not locating correct p element

jQuery .closest not locating correct p element


I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.

As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest p element (which is the element that houses the img element) b and add that the class CM-blog-image. Why isn't this working?

if($('.entry-content p img').hasClass('size-full')) {            $(this).closest('p').addClass('CM-blog-image');  }  

HTML

// <-- Need to add class to this p element

Answer by teshvenk for jQuery .closest not locating correct p element


If you have p tag and image tag immediate next of entry-content class. Use like below. it should work.

if($('.entry-content > p > img').hasClass('size-full')) {            $(this).closest('p').addClass('CM-blog-image');  }  

Answer by kravits88 for jQuery .closest not locating correct p element


I assume you want to add class to each element found.

$('.entry-content p img').each(function(){      if($(this).hasClass('size-full'))          $(this).closest('p').addClass('CM-blog-image');  });  

Answer by Bhojendra Nepal for jQuery .closest not locating correct p element


You can simply use like this:

$('.entry-content img.size-full').parent().addClass('CM-blog-image');                 //or you may use   ^^ closest('p')  

Answer by Satpal for jQuery .closest not locating correct p element


You can achieve it using simple traversal methods. No need to use .each()

$('.entry-content p img.size-full') //Find image with the class       .closest('p') //Traverse up to paragraph element       .addClass('CM-blog-image');  //Add the required class  

Answer by Ramanlfc for jQuery .closest not locating correct p element


//select img with class size-full   var elm = $('.entry-content p img.size-full');      // add CM-blog-image to closest parent p   elm.closest('p').addClass('CM-blog-image');  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.