Trying to display none, only hiding first instance of div - javascript

I have dynamically generated content which I'm outputting using two divs:
<div id="data1">Some info</div> -- <div id="data2">different info</div>
I want to only show "data2" in certain instances, so I'm trying to use JavaScript to hide it when it's not needed. Basically, my code is:
var getDivs = document.getElementById('data2');
IF STATEMENT {
getDivs.style.display='none'; }
However, this is only kind of working - it's hiding the very first div that it comes across, but it's not hiding ALL of the divs with that ID.
This means that my code is basically correct - the IF STATEMENT is working, the display='none' DOES hide something, it's just not hiding everything that it should...
I tried to change it from div id= to div class= and instead use document.getElementByClassName('data2') but that doesn't seem to be working at all - it doesn't even hide the first .
What am I missing / doing wrong? What do I need to change to get this to hide all of the divs that are "data2"?
Thanks!

Your code seems fine. You can see it works: http://js.do/code/zeek
Later Edit:
Using class instead of id:
<div id="data1">Some info</div> --
<div class="data2">different info</div>
<div class="data2">different info</div>
<div class="data2">different info</div>
<script type="text/javascript">
var getDivs = document.getElementsByClassName('data2');
for(var i= 0; i< getDivs.length; i++){
var div = getDivs[i];
div.style.display='none';
}
</script>

Use jQuery and select by class instead of by ID. See http://api.jquery.com/class-selector.
jQuery is not only easy and readable, you'll also not write getElementByClassName instead of getElementsByClassName.

$('#data2').hide();
This assumes jQuery is on your page: http://api.jquery.com/
Note: You're going to have problems if this is dynamic and there are several elements with the ID of data2. Instead, use classes for selecting relevant divs if you can help it.

Related

Finding the next type of element after a selector in jquery

I am hoping to get some help with finding the next type of an element after finding an image with ends a specific way. So far, I've got it locating the images and beginning to run an each() function, but I can't get it to select the next input on the page.
Here's the code I have so far:
$("img[src$='sunglasses.jpg']").each(function( index ) {
$( this ).closest(".label_box").find("input[name^=happy_]").prop('value', '1');
$( this ).nextAll("input[name^=happy_").eq(0).prop('value', '1');
});
And an example of the HTML would be something like this:
<div class="image_box">
<img src="sunglasses.jpg">
</div>
<div class="label_box">
<input name="happy_1">
</div>
Essentially, I'm trying to select the input of happy_* in another div directly after finding a matching image.
Never mind, I figured it out! I just needed to add 2 .parent() functions to get up tot he correct div.
$(this).parent().parent().next('div').find("input[name^=happy_]")

jQuery code is hiding all content inside my div

I have the following code:
jQuery(document).ready(function($) {
$("ul.accordion-section-content li[id*='layers-builder'] button.add-new-widget").click(function() {
$("#available-widgets-list div:not([id*='layers-widget'])").css('display','none');
});
});
The idea is, when i click a button that contains the class "layers-builder", all divs in "available-widgets-list" that DO NOT contain the class "layers-widget" are hidden.
The problem I'm facing is that using this code also hides all the divs inside "layers-widget" (as not all of them have "layers-widget" in the id.
for example, here is a mockup markup:
<div id="some-id">
...
</div>
<div id="this-layers-widget-89">
<div id="hello"></div>
<div id="yes"></div>
</div>
In the above example, the first div "some-id" would be hidden, along with all the child divs inside "this-layers-widget-89"
How can I make it so that all the content within the div containing "layers-widget" still shows?
The ">" operator specifies that the div must be a direct child of #available-widgets-list:
$("#available-widgets-list > div:not([id*='layers-widget'])").css('display','none');
You should add a class instead of relying on finding parts of some-id but this will work also work: $('[id*="some-id"]');
You should also be using jquery's built in hide()method instead of css('display', 'none'). They do literally the exact same thing but using the built in methods is more readable.

Showing and hiding text on more than one place on a website by clicking a single link

I want to show and hide content on a webpage by clicking a link 'Click for More text'. While this works fine, my intention is to display more text in two places on the page at the same time.
How can I 'unhide' and hide two different div id's by one click?
<script type="text/javascript">
  function unhide(divID) {
    var item = document.getElementById(divID);
    if (item) {
      item.className=(item.className=='hidden')?'unhidden':'hidden';
    }
}
</script>
and the HTML:
<a href="javascript:unhide(‘content’);”>Click for More text</a>
<div id=“content” class="hidden">
hi
</div>
<div id=“content2” class="hidden">
how can i display this from the same link..?
</div>
Put them in one more div to wrap it and then show just that one
<a href="javascript:unhide(‘content_wrapper’);”>Click for More text</a>
<div id="content_wrapper" class="hidden">
<div id=“content”>
hi
</div>
<div id=“content2”>
how can i display this from the same link..?
</div>
</div>
If you are using jQuery, better idea would be to use classes, check the code below for example
HTML:
<button onclick="unhide('more_info')">
Click for More text
</button>
<div class="more_info hidden">
hi
</div>
<div class="more_info hidden">
how can i display this from the same link..?
</div>
Javascript:
function unhide (arg) {
// toggle class, or remove or add, what ever you need
$('.'+ arg).toggleClass('hidden');
}
EDIT:
To answer question posted by OP in comments.
When it comes to jQuery, most people use only couple of forms of selectors. You can visit this link to find out more about selectors.
For the basics, you are mostly going to be using 2 forms. Personally I use class selector in most cases which is '.selector'
What you can do with it means you use it in form of $('.classSelector') where classSelector can be any class you want to select.
Couple of examples
<div id="test-div-id" class="test-div-class">
<p class="paragraph paragraph-1">This is first</p>
<p class="paragraph paragraph-2">This is second</p>
<p class="paragraph paragraph-3">This is third</p>
</div>
For javascript, you can then use following
$('.test-div-class')
// returns the div by selecting it's class
$('#test-div-id')
// returns the div by selecting it's ID
So if you wanted to check the value of first paragraph you could do
$('.paragraph-1').html();
// returns 'This is first'
You can also select multiple things, let's say you want to hide all paragraphs, you could use .hide() function from jQuery.
$('.paragraph').hide();
// the selector returns collection of all nodes containing class 'paragraph'
// after that we apply function hide.
The last one works on all classes, so you could mix paragraphs and divs and spans and what not. That brings us to next selector, by type
$('p').hide();
// this selector will return every paragraph by type selection
And you can also use what I did in the answer, simple adding of strings
$('.paragraph-1').html();
// returns 'This is first'
var selectorAsAnVariable = 'paragraph-1';
$(selectorAsAnVariable).html();
// returns nothing since it didn't select anything
// this is same as writing $('paragraph-1').html() which would be type selection
// since you don't have type paragraph-1 it fails
$(.selectorAsAnVariable).html();
// this fails on syntax error because unexpected token
$('.selectorAsAnVariable').html();
// returns nothing since it didn't select anything
// this is because you would be trying to select elements which really have that class
$('.'+selectorAsAnVariable).html();
// returns 'This is first'
// this is because this is same as $('.'+'paragraph-1').html()
// which is same as $('.paragraph-1').html() which we know is an class selector
You can also mix them, but I would advise against it because of performance issues, code readability and other reasons, for example you can target div by class and filter paragraph-1 from there. But in most cases it is better to write your code in way that you can avoid that.
For more about the topic, check the link I provided. Also you can use the search to look for other function explanations there.
I hope this clarified things a bit :)

How do I use jQuery to hide an element with no class or ID... when the parent has no id either?

I want to use jQuery to work with events in a given search box. My issue is that
I don't know how to build the selector correctly, so that JQuery accepts it.
I think I'm getting confused because I need the second element in the list and need to select that one.
The runtime HTML looks like this: (Adapted from Chrome Developer tools, only the relevant class and IDs are shown. There are no IDs to be shown.)
<body class=km-ios7 km-7 km-m0 km-web km-black-status-bar km-vertical km-widget km-pane>
<div class="km-widget km-view">
<!-- Begin 3rd party control -->
<div class=class="km-widget km-view">
<div km-header>
<div class="km-content km-widget km-scroll-wrapper">
<div class=km-scroll-header>
<div class=km-scroll-container>
<div class="km-listview-wrapper">
<form class="km-filter-form">
<div class="km-filter-wrap">
<input type=search >
What I've tried
Since my event wasn't firing I assume my selector was wrong. I opened chrome developer tools after I did "inspect element". The bottom of the tools listed all the parent tags used for that element (with no class or ID). As a test, I've tried hiding the search box using the following:
$("div").hide(); // hides everything...
$("div div").hide(); // hides the wrong element on the page
$("input").hide(); // nothing
$(":input").hide(); // nothing... saw this example somewhere, don't understand it
$("input:text").hide(); // nothing... saw this example (http://stackoverflow.com/q/17384218/328397), don't understand it
I looked at this W3 document, but didn't see what I was looking for (unless I missed it)
Any assistance in getting the right selector would be appreciated.
In the page you linked it's the second div under defaultHomecontent, so
$("#defaultHomeContent div:nth-child(2)")
You actually want to hide the div with class km-filter-wrap.
A safer alternative may be to not deal with selectors and instead show/hide the wrapper element for the ListViewFilter's searchInput element:
var listView = $("#local-filterable-listview").kendoMobileListView({
...
}).getKendoMobileListView();
listView._filter.searchInput.parent().hide();
or
listView.wrapper.find(".km-filter-wrap").hide();
In general, it's a good idea to use the elements that are exposed by Kendo UI controls as much as possible instead of manually building queries (since they might change in future versions).
You could also extend the ListView widget with your own API method for this:
kendo.mobile.ui.ListView.fn.filterVisible = function(value) {
var wrapper = this._filter.searchInput.parent();
if (value) {
wrapper.show();
} else {
wrapper.hide();
}
};
then you could use
listView.filterVisible(false); // hide the filter
you can use the find function. Let suppose you have input field inside footer div like this.
<div id="footer">
<div>
<div>
<input type="text" name="text" value="Search" />
</div>
</div>
</div>
You can use selector like this $("#footer input").hide() or $("#footer").find("input").hide() or $('input[name=text]', '#footer').hide();
Based on what you have added.
You could use
$("input[type='search']")
as a selector.
See if that helps. Here is an example
You could also combine the selectors in this manner:
var $container = $("div.km-widget");
var $searchBox = $container.find("input[type='search']");

Passing HTML and CSS to Javascript

I need to find a way to pass the visible div to javascript. This may not even be the best way to accomplish what I'm trying to accomplish, so I'm open for other suggestions.
All my site content opens in a single overlay. When a button is clicked in the navigation, that content opens in the overlay. When another button is clicked, that content replaces the current content in the overlay. And so on.
The best identifier (that I've spotted) of which overlay is open, is (CSS) display:block...and all the hidden divs are display:none....
So I want to pass which div has the display:block to javascript (Note: all the div's have unique ID's)
I'm sure this is something easy, But I can't seem to find it...
Thanks in advance for your time!!
Each HTML element in JS has style property. You can read and change element style by calling for example
document.getElementById('id').style.display
So you don't need to pass anything to JS, it's already there.
By reading your question it sounds like you need to identify which of your divs is the visible one. The easiest way to do that is add a class to all your divs with content, you can then use document.getElementsByClassName() to get a list of them and loop through to find which one is visible one based on a display property of block.
<div class="content" style="display: none";>a</div>
<div class="content" style="display: block;">b</div>
<div class="content" style="display: none";>c</div>
<div class="content" style="display: none";>d</div>
<div class="content" style="display: none";>e</div>
var elements = document.getElementsByClassName("content");
for(i = 0; i < elements.length; i++)
{
if (elements[i].style.display == 'block')
{
// elements[i] = this is the visable div
alert('This elements[i] has a display of block; contents = ' + elements[i].innerText);
}
}
The above script will output/alert 'b' as it is the visible div found.
Fiddle link

Categories

Resources