jQuery - iterate through all elements with class and change their style - javascript

I know this is supposed to be simple, but I'm running into multiple problems. First of all, I don't know how to get all elements of a class and change their display. I found the .each method with this sample code:
$('.classname').each(function(index) {
alert(index);
});
What do I need instead of the alert to change the display property of an element from 'none' to block'?
The second problem is, the class name is gathered from a hidden field. Let's name this variable service. When I try to replace the '.classname' with '.'+service I get an error saying 'Syntax error, unrecognized expression: .'.
So the actual code would be something like:
var service=$('#service').val();
$('.'+service).each(function(index) {
alert(index);
});
I'm sure this can't be complicated but I can't figure it out.
Any alternative solution is of course welcome.

Check out .show:
var service=$('#service').val();
$('.'+service).show(); // roughly equivalent to .css('display', 'block');
However, as the documentation for show points out, the method returns the matched elements display property to it's previous state. To explicitly change the display style property to block, use .css:
$('.' + service).css("display", "block");

try fadeIn() and fadeOut()
var service=$("#service").val();
$("."+service).fadeIn();

Related

How to hide a certain class in JavaScript

I don't know why this is not working. I am trying to hide a certain class and this is the only line of code I have on Javascript:
document.getElementsByClassName("popular").style.display = "none";
For some reason I get the error:
"document" is not defined.
What does that mean, it's not a variable.
Please help and thank you.
getElementsByClassName method returns ALL elements with the same class, think of it as an array of elements with the same class. So you need to specify, which element do you want to hide. In my example, I have only one element with such class, so I'm selecting it like the first element of an array ([0]). Your code should look like this:
document.getElementsByClassName("popular")[0].style.display = "none";
console.log('Current "display" property value is: ' + document.getElementsByClassName("popular")[0].style.display)
<div class="popular">TARGET</div>

Add Class to Array of ID's in Javascript

I am using .map to get an array of element IDs (this is named 'ids') that have a 'default-highlight' class. After removing that class on mouseenter, I want to return that class to those specific id's (basically, leave it how I found it).
Two things are causing me trouble right now:
When I dynamically add data-ids to the td elements and then use those data-ids to create the array of 'ids' my mouseenter stops adding the 'HIGHLIGHT' class (NO idea why this is happening)
On mouseleave I can't loop through the 'ids' and return the 'default-highlight' class to the elements they originally were on
I figure I should be using something like this, but it obviously isn't working:
$.each(ids, function() {
$(this).addClass('default-highlight');
});
I have tried a number of things, but keep coming up short. I am attaching a link to a codepen.io where I use data-ids that are being dynamically added to the table (this one the mouseenter doesn't work) and a codepen one where I am using regular IDs for the default highlight and everything appears to work like it is supposed to be (It isn't, since I want to be using the dynamically generated data-ids and then the subsequently produced array to reapply those classes).
Both of these codepens have a gif at top showing how the interaction should work.
If anything is unclear, please let me know. Thanks for reading!
You need to add # before id selector
$.each(ids, function() {
$('#'+this).addClass('default-highlight');
});
or you can use common selector by the help of map() and join()
$(ids.map(function(i, v) {
return '#' + v;
}).join()).addClass('default-highlight');
or you can add # when getting the id's and then you just need to join them
var ids = $('.default-highlight').map(function(i) {
return '#'+$(this).data('id');
}).get();
...
...
...
$(ids.join()).addClass('default-highlight');
It seems like storing the IDs and using those is overkill when you can store a reference to the jQuery element directly:
$highlightCells = $('.default-highlight').removeClass('default-highlight')
And later give the class back:
$highlightCells.addClass('default-highlight')
Here's a codepen fork: http://codepen.io/anon/pen/ZbOvZR?editors=101
Use this way:
$.each(ids, function() {
$("#" + this).addClass('default-highlight');
});

Im forcing to use getElementsByClassName()[] rather than getElementByClass()

I have 8 divs with id="div1","div2","div3".... and a class=divs. I also have a button with class="div1","div2","div3"......
When I click the button with id="div1", it will first remove all the class="selected" to all div that has a class="divs" then only the div with id="div1" will have the class selected. And so on.....
I want to use document.getElementByClass() for removing class but it don't work in my FIDDLE. :(
Instead, Im forced to use document.getElementsByClassName()[]. But it seems so hard to code since it requires me to put the specific arrays for the classname.
This is exactly I want to achieve FIDDLE
There is no getElementByClass for a reason: unlike id, class is not specified to be unique in a document. Which element would you get? No, you need the ability to get all of them. And if you get an array, that's solved by looping, not by repeating rows for each index:
However, your design is inefficient; and if you're already using jQuery, you can write it very tightly. This would be better:
<button class="divbuttons" data-div="div1">div1</button>
<button class="divbuttons" data-div="div2">div2</button>
...
then you can:
$(document).ready(function(){
$('.divbuttons').click(function() {
var div = $(this).data("div");
$('.divs.selected').removeClass('selected');
$('#' + div).addClass('selected');
});
});
This is an easy one. There is no document.getElementByClass
You have document.getElementById or document.getElementByClassName
There's no such thing as getElementByClass() because multiple elements can have the same class. There's getElementById() (elements have unique ids, or at least they're supposed to) and getElementsByClassName(), which returns an array of all elements that match the class specified.
try
$(document).ready(function () {
$("button[class^=div]").click(function () {
$(".divs.selected").removeClass("selected");
$("#" + $(this).attr("class")).addClass("selected");
});
});
DEMO

jQuery .addClass() and .removeClass() only applies to first instance of the element

I have the following code below:
<script type="text/javascript">
var $info = $('#thumb');
enquire.register("(max-width: 480px)", {
match: function() {
$info.removeClass('col-xs-6');
$info.addClass('col-xs-12');
},
unmatch: function() {
$info.removeClass('col-xs-12');
$info.addClass('col-xs-6');
}
}).listen();
</script>
I am using Enquire.js to dynamically add and remove css classes from elements.
The above code works but only for the first '#thumb'. I have about 12 elements which have the thumb id. Anyone know how I can apply it to all elements with the same ID
You have to use a class. ID's are unique so they can only apply it once. If you do: $('.thumb') then you will be fine.
It might be helpful for you to run your source through an html validator, which would help point out that it's not valid to have more than one element with the same id. Which is why it's only updating the first of your 12 elements.
Take a read through this http://css-tricks.com/the-difference-between-id-and-class/ is one quick reference that can hopefully explain the what/why/how of what's going on here.
#xxx is get by id. and you need to make sure this id is unique. If you want to get by class is .xxx for get by class, you will get it in array. So need to to use for-loop to addclass or removeclass

How to use in jQuery :not and hasClass() to get a specific element without a class

I have this line of code:
$('#sitesAccordion .groupOfSites').click(function() {
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
console.log(lastOpenSite);
});
I get "false" instead of getting one of the other elements (assuming that there is one - and there must be). I guess the problem is with:
.hasClass(':not(.closedTab)');
What is the problem?
My purpose is to create my own accordion (without using jQuery UI)
and I am trying to write it like this:
$('#sitesAccordion .groupOfSites').click(function() {
//Get the last opened tab
var lastOpenSite = $(this).siblings().hasClass(':not(.closedTab)');
//Close last opened tab and add class
lastOpenSite.hide().toggleClass('closedTab');
//Open the current Tab
$(this).children('.accordionContent').toggle('fast');
// remove class from open tab
$(this).toggleClass('closedTab');
});
Is this the best way?
thanks,
Alon
Use the not function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.
It's much easier to do like this:
if(!$('#foo').hasClass('bar')) {
...
}
The ! in front of the criteria means false, works in most programming languages.
jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
You can also use jQuery - is(selector) Method:
var lastOpenSite = $(this).siblings().is(':not(.closedTab)');
I don't know if this was true at the time of the original posting, but the siblings method allows selectors, so a reduction of what the OP listed should work.
$(this).siblings(':not(.closedTab)');

Categories

Resources