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/
Related
You need to put items in a div - <div style = 'flex-direction: column;'>.
Div needs to be created after p withid = "billing_city_field"
and closes after the p withid = "apartment_field".
Tried to do it with this function:
jQuery (document) .ready (function ($) {
$ ("# billing_city_field"). after ("<div style = 'flex-direction: column;'>");
$ ("# apartment_field"). after ("</ div");
});
But the div immediately closes. What should I do?
The issue is because you cannot append start/end tags separately. The DOM works with elements as a whole, so you need to create the entire div element in a single operation.
Given the description of your goal it looks like you're trying to wrap the existing content in a new div. As such you can use nextUntil() (assuming the target elements are siblings) and then wrapAll(). Try this:
jQuery($ => {
let $contents = $("#billing_city_field").nextUntil('#apartment_field').add('#apartment_field');
$contents.wrapAll('<div class="column" />');
});
Note the use of a class attribute in the above example, instead of applying inline style rules.
Question is not super clear but from what I can tell.
I think you have small misunderstanding what .after does with jQuery. After in this case is "structural" and not "time" related. If you check jQuery docs (https://api.jquery.com/after/) for this you can see basically what you need to do.
Simplest way to do this, if these things needs to created and don't exist already on body for example.
$(function(){
var p = $("<p id='apartment_field'>Paragraph test</p>");
$("body").append("<div id='billing_city_field' style='flex-direction: column;'></div>");
$("#billing_city_field").html(p);
});
I've added Paragraph test so result is visible easier.
And one more thing, not sure if it's error with copy/paste but make sure that # and id don't have space in-between like this.
$("#billing_city_field")
$("#apartment_field")
Edit: Looking at the comments maybe something like this, if they exist already? You should clarify the question more.
$("#billing_city_field").append($("#apartment_field").detach());
new here and deeply hoping I'm not missing a stupid syntax flaw. I was thinking that my problem is a fairly common one, but somehow nothing has helped so far in my specific case.
There is a simple inline-block list of Image Galleries which are zoomable to fill the parent width. As soon as one is zoomed through click on a child, the others should unzoom by stripping of the class which maximizes them. Nothing more to it.
I achieved the first part via the following jQuery (where the problem is hidden in the for-loop, I think):
$(".zoom").click(function() {
var target = $(this);
target.closest('div.product-item').toggleClass('maximized');
var ot = document.getElementsByClassName('product-item');
for (var i = 0; i < ot.length; i++) {
if (ot[i] !== target) {
ot[i].removeClass('maximized');
}
}
});
So: Some .zoom classed element is clicked, its parent is toggled to maximize and a for loop checks all other elements of the same class as the parent and removes the .maximized class.
The reason the script is constructed with a for-loop and a removeClass is so that the same .zoom elements are able to minimize their parent elements, not only to maximize them.
Im not a javascript professional, but to my knowledge this should work in principle. Am I missing anything here?
This post from a year ago addressed a similar problem but didn't help in my case: jQuery onClick: How to add class to element and remove from all others
You can find a pen to see the script in action here.
$(".zoom").on('click',function() {
var target = $(this);
$('div.product-item').removeClass('maximized');
target.closest('div.product-item').toggleClass('maximized');
});
you can use
if(target.closest('div.product-item').hasClass('maximized')){
$('div.product-item').removeClass('maximized');
}else{
$('div.product-item').removeClass('maximized');
target.closest('div.product-item').addClass('maximized');
}
JSFIDDLE
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
first time posting here. I'm a beginner in jquery and i ran into some grey area. Hopefully i can find my answer here and learn from it also :)
So i have a let's say 10 different div. All has the same class. And everytime I click on the div it has to add another class (in this case background-color in css). For that I have this:
$(document).ready(function() {
$(".menucardmenu").click(function(){
if($(this).hasClass("menucardmenu")) {
$(this).addClass("backgroundmenucard");
}
else {
alert ("condition false");
}
});
});
But the question now is, how can i make that only one div can have that background-color (in my case backgroundmenucard). Depending one which div the user click, that div will have the background-color, and the previous div (that was clicked) should reset it back to normal. I can do it with this right?:
$(this).removeClass("backgroundmenucard");
does anyone know the answer to this???
Regards,
Andrew
try the following:
$(".menucardmenu").click(function(){
$(".backgroundmenucard").removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
});
Demo: http://jsfiddle.net/r2Sua/
(I remove the if because it's useless in this case)
Remove from all...
$(".menucardmenu").removeClass("backgroundmenucard");
Then add to this
$(function() // shorthand for document ready
{
var $divs = $('div.menucardmenu'), // standard jQuery "cache" idiom
BG_CLASS = 'backgroundmenucard'; // stay DRY, less prone to typos
$divs.live('click', function() // use .live to bind only 1 event listener
{
// remove the class from all divs
$divs.removeClass(BG_CLASS);
// add the class to this div
$(this).addClass(BG_CLASS);
}
});
});
The if($(this).hasClass("menucardmenu")) check is completely unnecessary since you're already selecting elements which have that class. It will always evaluate to true.
$('.menucardmenu').click(function(){
$('.menucardmenu').removeClass('backgroundmenucard');
$(this).addClass('backgroundmenucard');
});
Another option would be:
$(".menucardmenu").not(this).removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");
This way you don't remove and add the class to the specific (this) element
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";