简体   繁体   中英

hide divs using javascript

I would like to hide divs that have no ids associated with them using javascript. For example, in sharepoint .ms-globalbreadcrumb doesn't have an id.

frame = document.getElementById('frame1'); 
frame.contentWindow.document.getElementById('ctl00_PlaceHolderGlobalNavigation_PlaceHolderGlobalNavigationSiteMap_GlobalNavigationSiteMap').style.display='none'; 

The above code works for pieces that have ids but I am not sure how to achieve this for other divs with no ids.

Thanks,

You would make your life a lot easier using something that normalizes access to the DOM, so that the same code (for everything - forms, events, object properties, etc etc) works across all browsers. Using JQuery it's just:

$('div').hide();

to hide all divs...and there are a huge range of 'selectors' to refine your selection.

Case 1
If you want to hide all divs with no id then you would have to loop all divs and hide them based on that criteria. ( find the divs with the .getElementsByTagName() )

var alldivs = document.getElementsByTagName('div');
for( var i = 0; i < alldivs.length; i++) {    
       alldivs[i].style.display = "none";
    }

Case 2
If you want to find elements based on a class, like in your example the .ms-globalbreadcrumb then ( find the elements with the class with the .getElementsByClassName() )

var allbyclass = document.getElementsByClassName('ms-globalbreadcrumb');
for( var i = 0; i < allbyclass.length; i++) {    
       allbyclass[i].style.display = "none";
    }

( the getElementsByClassName will not work for pre IE9 versions of IE )

example with both cases at http://jsfiddle.net/gaby/H3nNr/


suggestion

Use jQuery which allows for a wide variety of selectors and complex traversing of the DOM to find what you want..

  • Case 1 in jQuery would be $('div:not([id])').hide();
  • Case 2 in jQuery would be $('.ms-globalbreadcrumb').hide();

If you can locate the divs in the DOM, then you should be able to hide them. For example, if a parent / grandparent etc div has an ID, you can go down the DOM tree using Javascript until you have found the element you want to hide.

var elem = document.getElementById("topelement");
var elem2 = elem.firstChild.firstChild;
elem2.style.display = "none";

JQuery has lots of selectors for making this kind of thing easy.

so theres other methods you can use you can get them by tagname or classes

 document.getElementsByClassName
 document.getElementsByTagName

they return list of elements you need to iterate threw

so your example shud be

var ellements = frame.contentWindow.document
   .getElementsByClassName("ms-globalbreadcrumb");
for(i in ellements) {
  ellements[i].style.display = "none";
}

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