简体   繁体   中英

JQuery does not hide div if p element is before it?

I am trying to make use of a JQuery snippet to hide some content on SharePoint. It works without the <p> element, but SharePoint has a lot of stuff in between the div so I think that's why it's not working.

JQuery:

jQuery(document).ready(function() {
jQuery(".ms-wpcontentdivspace").hide();
//toggle the componenet with class msg_body
jQuery(".ms-webpart-chrome-title").click(function(e)
 {
   e.preventDefault();
   jQuery(this).next("div.ms-wpcontentdivspace").slideToggle(200);
 });
});

Here's the working code:

<div class="ms-webpart-chrome-title"><h2><a href="http://google.com"><span>Hello</span>      </a></h2></div>
<div class="ms-wpcontentdivspace">Hi there. I am hidden</div>
<div class="ms-webpart-chrome-title"><h2>Another title</h2></div>
<div class="ms-wpcontentdivspace">More hidden stuff</div>

Here's the code that doesn't:

<div class="ms-webpart-chrome-title"><h2><a href="http://google.com"><span>Hello</span></a></h2></div>
<p>some text</p>
<div class="ms-wpcontentdivspace">Hi there. I am hidden</div>
<div class="ms-webpart-chrome-title"><h2>Another title</h2></div>
<div class="ms-wpcontentdivspace">More hidden stuff</div>

Here's a Jsfiddle . Thanks!

The jQuery version used 1.3.x is pretty old, anyway try

jQuery(document).ready(function () {
    jQuery(".ms-wpcontentdivspace").hide();
    //toggle the componenet with class msg_body
    jQuery(".ms-webpart-chrome-title").click(function (e) {
        e.preventDefault();
        jQuery(this).nextAll("div.ms-wpcontentdivspace").eq(0).slideToggle(200);
    });
});

Demo: Fiddle

$.next() only gets the immediately following sibling, so you will want to use $.nextAll()

jQuery(document).ready(function() {
jQuery(".ms-wpcontentdivspace").hide();
//toggle the componenet with class msg_body
jQuery(".ms-webpart-chrome-title").click(function(e)
 {
   e.preventDefault(); 
   jQuery(this).nextAll("div.ms-wpcontentdivspace").eq(0).slideToggle(200);
 });
});

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