This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get nth jQuery element
I have this simple code:
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
I know that my 2nd element should have a class active, how do I add this class?
this code won't work:
$('ul li').get(1).addClass('active')
I assume it is becuase it returns a dom element and not jquery element. but how do I do it right?
=======
Of course 2nd element is an example. I need each time to change the active class from a variable called theActiveClassNumber
$("ul li:nth-child(2)").addClass('active')
or
$("ul li:eq(1)").addClass('active')
get() returns a DOM element so you have to re-wrap in the jQuery object:
$( $('ul li').get(1) ).addClass('active');
you can do like #Kanishka answer that work to, but you can try this one too, may be can help you,
$("ul li:nth-child(even)").addClass('active');
$("ul li:nth-child(odd)").addClass('active');
Not a direct answer to the question, but:
If you want to get certain jQuery Object, you should use .eq() instead of .get().
Related
This question already has answers here:
jQuery - Appending a div to body, the body is the object?
(6 answers)
Closed 7 years ago.
I have the following code:
$('body').on('click' , function(){
$('body').append('<div class="ajax-success"><p>Its Done !!!</p></div>').fadeOut(2000);
});
My intent was to add the div and then remove it with a fadeout effect using the fadeout() function , now obviously the above code fades out the entire html document.
I have seen a few similar threads of SO, but they are with the fadeIn effect and the solution does't apply , also i checked the documentation and there is no callback function available for the append() and appendTo() which could have been a posible solution to my problem, so how do i go about fading the div that i added using the append() method ?
Use appendTo as this will return the appended div instead of body:
$('body').on('click', function(){
$('<div class="ajax-success"><p>Its Done !!!</p></div>').appendTo( this ).fadeOut(2000);
});
Your target is body so that is what fades out. Find a way to target the div you want. One of the easiest ways would be:
$('body').append('<div class="ajax-success"><p>Its Done !!!</p></div>')
.find('.ajax-success')
.fadeOut(2000);
This presumes there is only one 'ajax-success'-classed element on the page. If more, find a way to make your addition unique.
I'll just give a quick example to illustrate what I mean with the question. Say your HTML looks like this...
<div class="tabPanels">
<ul class="tabs clearfix">
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
How do I target the all the a tags in JavaScript? I understand that in jQuery you would do the following
$('.tabs li a').click(function(){
//jquery code here
});
How would I do the exact same thing with pure JavaScript?
Of course I could just do...
document.getElementsByTagName('a');
However suppose I have multiple li a tags in my webpage, I don't want to target all of them, only a specific set such as the ones above. Sorry if this is a dumb question. JQuery makes things easy, but I would like to do better with pure javaScript.
You have document.querySelectorAll function to do that: querySelectorAll
Note that is IE8+ function, but in this browser you only use it with CSS2 selectors.
Regards.
This question already has answers here:
Setting CSS pseudo-class rules from JavaScript
(12 answers)
Closed 8 years ago.
Hi I have this click function to show a :before and for some reason it wont show it ? Here is my code thank you!
Also the .cart-toggle:before class is display:none; so it can show.
$( ".cart-toggle" ).click(function() {
$( ".cart-toggle:before" ).show( "slow", function() {
// Animation complete.
});
});
Thank you !
jQuery (and javascript in general) does not support CSS pseudo classes as they are not part of the DOM.
The workaround depends on what you're trying to do, but animating a pseudo class with jQuery is pretty much not possible, so I'm guessing you would have to create an actual element instead of the pseudo class.
Every CSS selector is not allowed in jQuery. Only a little bit of them are allowed, for example . class selector, # id selector, :first-child child selector.
Other than that, jQuery has its own methods of selecting elements of type. Like :checkbox (https://api.jquery.com/checkbox-selector/)
Other CSS selectors are not valid in jQuery.
So you can't do exactly what you want, but you can show/hide your :before in CSS based on a class, and then add that class later on to show it. Example:
Fiddle
HTML
<p>Example</p>
CSS
p.toggled:before {
content: "show-me";
}
JQUERY
$("p").on("click", function() {
$(this).toggleClass("toggled");
});
This question already has answers here:
What's the difference between '$(this)' and 'this'?
(7 answers)
Closed 8 years ago.
I've been reading quite a bit now, but I still haven't gotten a explanation that would make sense, from a noobs perspective.
$(document).ready(function() {
$("#slideshow").css("overflow", "hidden"); /*kuna JS t66tab siis ei ole vaja scrollbari n2ha*/
$("#slideshow-nav").css("visibility", "visible"); /*nupud tehakse n2htavaks*/
$("#slideshow-nav a[href=#pilt1]").addClass("active"); /*muudetakse esimene nupp aktiivseks*/
$("#slideshow-nav").localScroll({ /*see funktsionaalsus pärineb ka http://flesler.blogspot.com/*/
target:'#slideshow', axis: 'x' /*vajalik scrollTo ja localscroll kasutamiseks, paneb paika,et need pluginad liigutaksid slaidi pilte mööda x-telge*/
});
$("#slideshow-nav a").click(function(){
$("#slideshow-nav a").removeClass("active");
$(this).addClass("active"); /*kui vajutada uuele nupule v6etakse aktiivne klass sealt 2ra ja lisatakse vajutatud nupule*/
});
});
What purpose does $(this) have in context to this: $(this).addClass("active");, I understand what the code itself does, but what is the purpose for $(this), if $(this) wouldn't be used there, is there a easy way of achieving the same effect?
Thanks!
$(this) refers to the the jQuery element that was clicked. Using $(this) is a surefire way to ensure you're referencing the element that was the user interacted with. Unfortunately there is no good way to ensure that you're referencing the element you interacted with without using $(this)
First let's start with what this means. In JavaScript, any function can be bound so that this refers to an arbitrary thing (object, number, string, etc.) inside of the function when it's called (refer to Function.bind). In general there are no assurances of what this will refer to inside of an arbitrary function; you'll have to read the documentation/source code or test for yourself.
When you call click(), jQuery is binding this in your callback function to a target element in the matched set. When you say $(this) (or jQuery(this)), you're simply wrapping the element with a jQuery "wrapper".
As for alternatives, jQuery will pass the event object to your callback, and you can access the target through that:
$("#slideshow-nav a").click(function(evt){
console.log($(evt.target)); //I think just using "$(this)" is easier!
});
See jQuery $(this) vs this.
$("#slideshow-nav a").click(function(){
$("#slideshow-nav a").removeClass("active");
$(this).addClass("active");
});
When the handler function you passed to $("#slideshow-nav a").click() is called, this is bound to the element that fired the event. You then pass this to $() to construct a jQuery object around that element, so you can use jQuery's addClass() on it. You could accomplish the same thing by replacing that line with this.classList.add("active"), to use the non-jQuery way to do the same thing.
Long story short, you use $(this) when this is bound to some element and you want to use jQuery methods on that element.
So, what this code ultimately does is:
Remove the class "active" from all elements matching the selector #slideshow-nav a.
Add the class "active" to the element receiving the event (the clicked element).
In this manner, any previously "active" element is "deactivated", and the clicked one is "activated".
Per minitech's comment, $(this) refers to one of the 'a' elements in the slideshow-nav DOM element, specifically the one that was clicked.
$("#slideshow-nav a").click(function(){
// $("#slideshow-nav a") refers to an array of links in slideshow-nav
$("#slideshow-nav a").removeClass("active");
// $(this) refers just to the specific link that was clicked
$(this).addClass("active");
});
This is best practice AFAIK. Is there some reason you do not want to use $(this)?
I use .append to add to a div
$(this).append('<ul><li>test</li></ul>');
how can I search for a <ul> and remove it if it exists in the children of $(this)?
You could use remove(). More information on jQuery remove().
$(this).children("ul").remove();
Note that this will remove all ul elements that are children.
The opposite of .append() is .prepend().
From the jQuery documentation for prepend…
The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).
I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.
Use the remove() method:
$(this).children("ul").remove();
What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:
var newUL = $('<ul><li>test</li></ul>');
$(this).append(newUL);
// Later ...
newUL.remove();
just had the same problem and ive come across this - which actually does the trick for me:
// $("#the_div").contents().remove();
// or short:
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");
Opposite up is children(), but opposite in position is prepend().
Here a very good tutorial.