A quick way of hiding divs? - javascript

I have the following line of code
document.getElementById("divName").style.display = "none";
How do I hide a bunch of layers at once with totally different names without writing the line of code that often?
Thanks

Felix's thoughts are good. There's a third way: Since they all share a common ancestor (body), you can hide them by adding a class to body and having rules in the CSS that match the actual elements in question, like so:
body.foo table {
display: none;
}
That would hide every table on a page if you added the class "foo" to body, like this:
document.body.className += " foo";
...and then show the tables again if you removed it:
document.body.className =
document.body.className.replace(/\bfoo\b/, '');
Live example
Naturally, that selector can be a lot more discerning:
body.foo div.magic > table {
display: none;
}
That would only hide table elements that were immediate children of a div with the class "magic" (and only when body had the class "foo").
Off-topic: If the approach above doesn't suit (and it doesn't suit a lot of situations), JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others can make manipulating sets of elements (in the ways that Felix mentioned) dramatically easier than going it alone.

Option 1 -- Create a function
function hideDiv(divname) {
document.getElementById(divname).style.display = "none";
}
Option 2 -- Hide a parent element
If all of the elements can be put inside of a parent element or already are, you can simply hide that parent element.
Option 3 -- Use a framework
A javascript framework like jQuery or MooTools will have a convenient coding convention such as .hide()
jQuery: -- see http://api.jquery.com/hide/
mooTools -- see http://mootools.net/docs/more/Element/Element.Shortcuts
Also, frameworks have tools for more complex situations and will allow you to select children of elements or a particular class and iterate through them. They can come in very handy when working with a page that has dynamically created content.
`
// jQuery Example 1: class-hiding
$(".elementsToHide").hide()
// jQuery Example 2: hiding divs within element "#whatever"
$("div", "#whatever").each(function() {
$(this).hide();
});

If they all have the same parent/ancestor, hide the parent (if possible).
Get the references to that elements, put them into an array and loop over them.

var divsToHide = ["thisDiv", "thatDiv", "divName"];
for (var i=0; i<divsToHide.length; ++i)
{
var div = document.getElementById(divsToHide[i]);
if (div) div.style.display = "none";
}
Or, you could use a framework like jQuery, and give the hidden divs some attribute in common, like a class of "hidden". Then,
$(".hidden").hide();
Course, in that case, you could also just set display: none on the class via CSS.

If they are from the same class you could select all elements of that class and loop through them. If they are all of the same parent you can select all the children, loop through them, filter if necessary and hide them this way.

var names = ['divName1', 'divName2','divName3'];
for ( i in names ) document.getElementById(names[i]).style.display = "none";

Related

Jquery Mobile Filter system, can't hide multiple divs

I'm making a Jquery Mobile app and have a page with 15 or so divs with class', I'm trying to make a filtering system so that when you press a button some of these divs disappear depending on the class. There are 3 groups and they all have an "all" class to display everything making 4 classes total.
Unfortunately most of the js I use never works even if I set up a jsfiddle for jquery mobile when I put it into my app it doesn't seem to work.
I wanted to use
function show(target) {
document.getElementsByClassName(target).style.display = 'block';
}
function hide(target) {
document.getElementsByClassName(target).style.display = 'none';
}
But that doesn't work whereas document.getElementById seems to work fine. However obviously I can only hide/show 1 div per button..
I was wondering if there was a work around for this or something completely different I should try?
Here's a jsfiddle of what I have: http://jsfiddle.net/tzcx7gky/
It's completely broken in jsfiddle but it works fine in my code, which is odd..
You don't need seperate hide - show functions. The following would take care of all.
$('a').on("click",function()
{
$("#scroll_content div").hide(); // initially hide all divs inside the element with id = scroll_content
var target = $(this).text().toLowerCase(); // find the class you wish to show using the text of the a tag clicked ( I would prefer using data-attr in this case but I'll leave the choice upto you.
$("." + target).show(); // show the element with the class target.
});
Working example : http://jsfiddle.net/tzcx7gky/2/
getElementsByClassName returns an array of elements. So you would have to itterate over the array and then set the display property on each one. Since you are already using jQuery you can use it to do it for all the elements.
function show(target) {
/* jQuery uses CSS selectors to grab elements
so we have to prefix the target with "."
Alternativley we could pass in the whole selector in the
function so we don't have to prefix it e.g.
show('.all')
$(target).show();
*/
$("."+target).show();
}
function hide(target) {
$("."+target).hide();
}
Here is the same implementation in the vanilla js framework
function show(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'block';});
}
function hide(target) {
var elements = document.getElementsByClassName(target);
elements.forEach(function(element){element.style.display = 'none';});
}
note that getElementById returns a single element since id's are unique and there should only be one element with one id on the page. That is why it was working for you.

Cannot select all elements except one

I am trying to select all the elements of a page except one, inside a function:
$('#sidebutton').click(function () {
if (!$('.sidemenu').hasClass("current")) {
prevScrolPos = $(window).scrollTop();
scrollTo = 0;
} else {
scrollTo = prevScrolPos;
}
$('.hidelem').toggleClass("hidden");
$('.sidemenu').toggleClass("current");
$('html,body').scrollTop(scrollTo);
});
It works when I use a simple class selector (.hidelem), but doesn't when I use something a bit more complicated (for example, $("*:not(.sidemenu)").toggleClass("hidden"); or $("*").not(".sidemenu").toggleClass("hidden");); these just lead to a blank window.
Could you tell me what I'm missing here?
JSFiddle: https://jsfiddle.net/et978wjw/5/ (full functionality is missing but I hope you get the idea)
The problem is that you may be skipping .sideMenu with $("body *:not(.sidemenu)"), but you are not skipping its parent DIV. If you hide an ancestor, you hide all its descendants too. You also do not skip any descendants, so the children of .sidemenu are also hidden
So you need to exclude anything that is an ancestor of .sidemenu with :not:(has()), then exclude the sidemenu itself, then exclude any children of sidemenu:
$("#container :not(:has(.sidemenu)):not(.sidemenu):not('.sidemenu *')").toggleClass("hidden");
JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/8/
You really should direct the hide/show at something more specific though. Perhaps a wrapper div around everything you want hidden? I added one for the demo.
Now having said all that, your selection process is quite complicated. You would be better off simply adding a class to all the things you want to toggle instead and just toggle those (you already have nodisplay on the divs, so I used that for now).
e.g. just this:
$(".nodisplay").toggleClass("hidden");
JSFiddle: https://jsfiddle.net/TrueBlueAussie/et978wjw/9/

find siblings and addclass using javascript only

I want to add class on siblings of target Element in javascript. I have done this before using jquery which is pretty easy. But In my current organization they do not use jquery and I need to done with javascript and that is very difficult for me.
I have write some code that will attached a click function to an matched element but afterward I am not getting any login to how to make it happend. fiddle
var elements= document.getElementsByTagName('*'),i;
i=0;
while(elements[i]){
if(elements[i].className=='c'){
elements[i].addEventListener('click',function(){
this.jsSiblings().jsAddClass('newClass')
})
}
i++
}
Array.prototype.jsSiblings= function(){
//code
}
Array.prototype.jsAddClass=function(){
//code
}
You can use the base function in JS to add a class, element.classList.add("anotherclass"); (from MDN) and here you will find out about siblings without jQuery : How to find all Siblings of currently selected object

select html object without id

Edit: one missing piece of information - I can't use the class selector because there are more divs with the same class. I already thought of that, but I forgot to mention it. I have no idea why my post got downvoted, but it seems awfully silly considering I provided a lot of information, gave it honest effort, and tried to be verbose with code examples. People on this forum are ridiculous sometimes.
I'm trying to set the id of a div that doesn't have one and there's no way I can give it one upon generation of the page. I've tried using jquery (.each, .contains, .find, .filter, etc.) and I can't seem to get it right. I know a ton of people have asked this question, but none of the answers made sense to me.
I have the ability to set the text (html?) of the div, but nothing else. It ends up looking like this:
<div class="dhxform_note" style="width: 300px;">Remaining letters: 500</div>
I want a handle to the div object so I can show the user how many more letters they can type by updating the text.
Using this:
$("div")
returns a list of all divs on the page. I can see the target div in the list, but I can't get jquery to return a single object.
I know it can also be done with something like this:
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++) {
if( /^Remaining letters/.test(divs[i].innerText) )
divs[i].id = "kudosMsgNote"
}
}
but I was hoping to complete this with a cleaner looking solution involving jquery. I also simply want to know how to do it with jquery, aesthetics not withstanding.
Use a class selector.
var theDivViaTheClass = $(".dhxform_note");
Class Selector (“.class”)
Description: Selects all elements with the given class.
version added: 1.0
jQuery( ".class" )
class: A class to search for. An
element can have multiple classes; only one of them must match.
For class selectors, jQuery uses JavaScript's native
getElementsByClassName() function if the browser supports it.
You seem to be targeting the <div> by its text. Try using the :contains selector:
$("div").filter(':contains("Remaining letters")').first().attr("id", "kudosMsgNote");
The .first() is to make sure you don't set the same id for multiple elements, in case multiple elements contain the text "Remaining letters".
Here's the docs for the :contains selector: http://api.jquery.com/contains-selector/
Be careful, the text you're looking for is case sensitive when using :contains!
Is that div the only one with the class dhxform_note? If so, you can use the class selector:
$('.dhxform_note').html();
With jQuery, you can specify any css selector to get at the div:
$(".dhxform_note").attr("id", "kudosMsgNote");
will get you this element as well.
Selecting on inner text can be a bit dicey, so I might recommend that if you have control over the rendering of that HTML element, you instead render it like this:
<div name="remainingLetters" class="dhxform_note" style="width: 300px">Remaining Letters: 500</div>
And get it like this:
$("[name=remainingLetters]").attr("id", "kudosMsgNote");
However, it's possible that you really need to select this based on the inner text. In that case, you'll need to do the following:
$("div").each(function() {
if ( /^Remaining letters/.test($(this).html()) ) {
$(this).attr("id", "kudosMsgNote");
}
});
If you cannot set id for whatever reason, I will assume you cannot set class either. Maybe you also don't have the exclusive list of classes there could be. If all those assumptions really apply, then you can consider down your path, otherwise please use class selector.
With that said:
$("div").filter(function() {
return /^Remaining letters/.test($(this).text())
}).attr('id', 'id of your choice');
For situations where there are multiple divs with the class dhxform_note and where you do not know the exact location of said div:
$("div.dhxform_note").each(function(){
var text = $(this).text();
if(/^Remaining letters/.test(text)){
$(this).attr("id", "kudosMsgNote");
}
});
EXAMPLE
If, however, you know that the div will always be the 2nd occurrence of dhxform_note then you can do the following:
$("div.dhxform_note").get(1).id = "kudosMsgNote";
EXAMPLE
Or do a contains search:
$("div.dhxform_note:contains('Remaining letters')").first().attr("id", "kudosMsgNote");
EXAMPLE

Select all elements that have a specific CSS, using jQuery

How can I select all elements that have a specific CSS property applied, using jQuery? For example:
.Title
{
color:red;
rounded:true;
}
.Caption
{
color:black;
rounded:true;
}
How to select by property named "rounded"?
CSS class name is very flexible.
$(".Title").corner();
$(".Caption").corner();
How to replace this two operation to one operation. Maybe something like this:
$(".*->rounded").corner();
Is there any better way to do this?
This is a two year old thread, but it was still useful to me so it could be useful to others, perhaps. Here's what I ended up doing:
var x = $('.myselector').filter(function () {
return this.style.some_prop == 'whatever'
});
not as succinct as I would like, but I have never needed something like this except now, and it's not very efficient for general use anyway, as I see it.
Thank you, Bijou. I used your solution, but used the jQuery .css instead of pure javascript, like this:
var x = $('*').filter(function() {
return $(this).css('font-family').toLowerCase().indexOf('futura') > -1
})
This example would select all elements where the font-family attribute value contains "Futura".
You cannot (using a CSS selector) select elements based on the CSS properties that have been applied to them.
If you want to do this manually, you could select every element in the document, loop over them, and check the computed value of the property you are interested in (this would probably only work with real CSS properties though, not made up ones such as rounded). It would also would be slow.
Update in response to edits — group selectors:
$(".Title, .Caption").corner();
Similar as Bijou's. Just a little bit enhancement:
$('[class]').filter(function() {
return $(this).css('your css property') == 'the expected value';
}
).corner();
I think using $('[class]') is better:
no need to hard code the selector(s)
won't check all HTML elements one by one.
Here is an example.
Here is a clean, easy to understand solution:
// find elements with jQuery with a specific CSS, then execute an action
$('.dom-class').each(function(index, el) {
if ($(this).css('property') == 'value') {
$(this).doThingsHere();
}
});
This solution is different because it does not use corner, filter or return. It is intentionally made for a wider audience of users.
Things to replace:
Replace ".dom-class" with your selector.
Replace CSS property and value with what you are looking for.
Replace "doThingsHere()" with what you want to execute on that
found element.
Good luck!
Custom CSS properties aren't inherited, so must be applied directly to each element (even if you use js to dynamically add properties, you should do it by adding a class), so...
CSS
.Title
{
color:red;
}
.Caption
{
color:black;
}
HTML
You don't need to define a rounded:true property at all. Just use the presence of the 'Rounded' class:
<div class='Title Rounded'><h1>Title</h1></div>
<div class='Caption Rounded'>Caption</div>
JS
jQuery( '.Rounded' ).corner();

Categories

Resources