I try to add CSS class to <li> element, when I click on the button but addClass not working.
Here is my JS:
$('.test').click(function(event) {
var centrum1 = $('.p17');
$('section.bok-map').find( centrum1 ).addClass('active-region');
});
And this how is looking HTML code:
Where is the problem? find() returns true.
Here is demo: http://demo.vrs-factory.pl/mapDemo/
You had a couple of errors, as you were not selecting the correct element, hence the length of the selector was 0.
Firstly, the class is called pl7 not p17 and secondly, when using removeClass you don't put the . before the name of the class. As you are using removeClass it is understood that you want to target a class, hence not requiring you to specify this by adding the dot.
<script>
var centrum1 = $('.pl7');
$('.test').click(function(event) {
$('section.bok-map').find( centrum1 ).removeClass('pl7');
});
</script>
Also, it may be worth noting that since you are only referencing$(.pl7) once you do not necessarily have to assign it to a variable. You could also write it as below. It is up to you.
$('.test').click(function(event) {
$('section.bok-map').find('.pl7').removeClass('pl7');
});
Related
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
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
I want to replace the old class of html element with the new one using jQuery. Here is what I'm doing:
var elem = $('.my_selector')[0];
elem.css('class', 'my_new_class');
But I get the error saying "Uncaught type error: Object#<HtmlDivElement> has no method css.
How do I fix it?
The problem is that you are trying to call jQuery method css() (even not relevant here) from DOM element, which is derived with [0]. You can use toggleClass() to do the job:
$(".my_selector:first").toggleClass("my_selector my_new_class");
$('.my_selector')[0] is returning you a DOM element, not a jQuery Object. You'll also want to use the addClass method rather than css. To get the first element, you can use the :first pseudoselector.
So this should be what you are looking for:
$('.my_selector:first').removeClass('my_selector').addClass('my_new_class');
EDIT You can use either removeClass/addClass or toggleClass. Either are fine. Explicitly adding the new class may be safer if you have a case where an element can have both classes at the same time since toggleClass will remove both classes.
var elem = $('.my_selector')[0];
This will return the DOM element, not a jQuery object. Simply change it to this...
var elem = $('.my_selector');
To get just the first element that matches the selector, use this...
var elem = $('.my_selector').first();
Also, you have...
elem.css('class', 'my_new_class');
This is incorrect and should be changed to this...
elem.attr('class', 'my_new_class');
Try this ,
var elem = $(".my_selector");
elem.class("newclass");
otherwise you can do,
var elem = $(".my_selector");
elem.removeClass("my_selector");
elem.addClass("newclass");
$(".my_selector").removeClass('currentClass').addClass('newClass');
As said, you need the jquery object of the first element. A good method could be this:
$('.my_selector').first().css('class', 'my_new_class');
Moreover the method signature is .css( propertyName, value ) so its intented to set a css property not to change a class. To do that you need to remove old class and add new one with .removeClass and .addClass respectively.
$($('.my_selector')[0]).css('class', 'my_new_class');
document.getElementsByClassName('my_selector')[0].className = 'my_new_class';
I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me.
<span class="a-class another-class test-top-left"></span>
I have an element (this code shows a span but it could be div span or anything). This element has a class beginning with test- (test-top-left, test-top-right etc.) I've triggered a click event on classes starting with test- and saved the clicked object as var object = this;. Simple stuff so far.
What I'm trying to do now is get the full name of that class (test-top-left). I know it starts with test- but what's the full name. The thing is that there are other classes a-class another-class and test-top-left. Can hasClass be used to get the full name of the class? I'd prefer not to use find() or filter() just because there may be additional elements within that also have class="test-"
Edit:
The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with test-.
var object = this;
$(object).attr('class');
So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.
Description
You can use jQuerys Attribute Contains Selector, .attr() and .click() method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
More Information
jQuery - Attribute Contains Selector
jQuery - .attr()
jQuery - .click()
jsFiddle Demonstration
This should work for you:
var object = this;
var className = object.className.match(/(test-.*?)(?:\s+|$)/)[1];
Class name is the name of the class you are looking for.
If you don't want to use split or regex, you can try having the class in a separate attribute
<span class="someclass test-something" _rel="test-something">test<span>
or
<span class="someclass" _rel="test-something">test<span>
with the script
$("[_rel*='test-']").click(....
And to retrieve the attribute, use $(this).attr("_rel")
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)');