jQuery get the previous span - javascript

I'm trying to get the previous span before the current, my code doesn't work.
<span class="badge votes">0</span>
<span data-vote="up" data-count="0" class="glyphicon glyphicon-thumbs-up"></span>
<span data-vote="down" data-count="0" class="glyphicon glyphicon-thumbs-down"></span>
What I want is when i click the span with class="glyphicon glyphicon-thumbs-up" and class="glyphicon glyphicon-thumbs-down" to get the value in span with class="badge votes"
here's my jQuery code
alert($(this).parent().find('span').text());
or
alert($(this).prevAll('.votes:first').text());

$('.glyphicon').click(function(evt) {
alert($(this).parent().prevAll('.badge.votes').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="badge votes">0</span>
<span data-vote="up" data-count="0" class="glyphicon glyphicon-thumbs-up">Up</span>
<span data-vote="down" data-count="0" class="glyphicon glyphicon-thumbs-down">Down</span>
Your parent().find('span') will go up to <a>, then look for a span in its children. prevAll('.votes:first') looks for sisters of the current span (which has no sisters). In both cases, you are stuck one level below from where you want to be.

You could use jquery's "closest" function to grab the span you are looking for like so:
$('span').on('click', function (ev) {
alert($(ev.currentTarget).closest('.badge.votes').html());
});
fiddle: https://jsfiddle.net/8xj3mt7k/

You could do it like this:
$(this).parent().siblings('.badge.votes');
It will select the sibling of <a> with badge votes.
span selector can also work.

Here's a dirty little trick:
$( "#up-vote, #down-vote" ).on( "click", (function( votesSpan ) {
return function() {
alert( votesSpan.text() )
}
}( $("span.badge.votes") )) )
Fiddle: http://jsfiddle.net/z4sbhmn9/
This can be taken even further and turn into a utility method.

Some of these answers are flat out wrong, but all are too complicated.
.closest('classname') will return itself, so this is wrong.
.parent() will return the PARENT class, so this is wrong.
The code you're looking for is $(this).prevAll('span:first').text()
or for this specific example, $(this).prev().prev().text();
I tested both of these, and they work. Just in general, think of it this way - you're navigating through HTML elements. Look in your browser console at the nodes and you'll see the page hierarchy. .next() and .prev() return the next sibling. .find() searches through children.

Related

Click event on <a> tag inside <span> tag in jquery

Im trying something simple, i am quite noob in jquery and i donĀ“t know how to make an click event when you click in an a tag that is inside a span tag, this is my code.
<span>
<a class="paginate_button current" aria-controls="table_id" data-dt-idx="1" tabindex="0">1</a>
<a class="paginate_button " aria-controls="table_id" data-dt-idx="2" tabindex="0">2</a>
<a class="paginate_button " aria-controls="table_id" data-dt-idx="3" tabindex="0">3</a>
<a class="paginate_button " aria-controls="table_id" data-dt-idx="4" tabindex="0">4</a>
</span>
I tried this but it doesn't work
$("#table_id_paginate > span > a.paginate_button").click(function() {
alert("Handler for .click() called.");});
The markup you provided does not have an element with the ID "table_id_paginate". So jQuery is selecting the links because it is looking for a elements with the class paginate_button who are direct descendants of a span that is a direct descendant of an element with that ID.
So if you change your code to how Tim Lewis commented: $(".paginate_button").click(...) the code works.
Just making this change will make it work, basically you want that any <a> tag with .paginate_button class should work on click.
<script>
$("span > a.paginate_button").click(function() {
alert("Handler for .click() called.");});
</script>
Edit :
How to go about these :
Figure out the target element, then keep going up towards the parent and
that becomes your target.
$("a.paginate_button").on("click", function () {
//your code here
})

Why isn't jQuery closest working

I am working on a small system that uses collapsable blocks - for this I am have a css class that toggles on or off depending on the jQuery dependancy.
The code I am using is:
$("#click_me").on("click", function () {
$("#clicked_action").toggleClass("show");
});
And this works, but is not what is needed. What is need is:
$(".collapse-header").on("click", function () {
$(this).closest(".collapse-body").toggleClass("show");
});
But this does not work.
I am not getting any console errors, so any help is apprecated
EDIT HTML value:
<div class="collapse-header" id="click_me">
<span class="float-left">Click me</span>
<span class="float-right"><span class="glyphicon glyphicon-plus"></span></span>
<hr class="hr" />
</div>
<div class="collapse-body" id="clicked_action">
I'm collapsed
</div>
You are looking for
$(this).parent().find(".collapse-body")
About .closest
$(element).closest(selector) is to find the first element which matches selector in traversing up through element's ancestors.
In your case, your elements are at the same level ("siblings") so .closest doesn't work.

Click event toggling all classes rather than correct block

I have some collapsed/collapsible blocks whereby the first block is open and second/third closed. They work the way I want in terms of opening and closing, but I can't get my head around how to alter the function so that the plus and minus icons change for the correct block. At the moment all change at the same time no matter which block I open or close.
How I can alter the function so that the toggled block updates the correct icon?
function toggleDiv(divId) {
$("#"+divId).toggle();
$('.product-toggle span.icon').toggleClass('icon-plus icon-minus')
}
HTML
<p><span class="icon icon-plus" aria-hidden="true"></span><span class="toggle-title">Features</span></p>
<div id="features">
Features
</div>
<p><span class="icon icon-plus" aria-hidden="true"></span><span class="toggle-title">Specifications</span></p>
<div id="specifications">
Spec
</div>
<p><span class="icon icon-plus" aria-hidden="true"></span><span class="toggle-title">FAQ</span></p>
<div id="faq">
FAQ
</div>
Let me start off by saying no... just no!
Add the target in your markup as a data attribute:
<div class="product-toggle" data-target="features">
<p>
<span class="icon icon-plus" aria-hidden="true"></span>
<span class="toggle-title">Features</span>
</p>
</div>
<div id="features">
Features
</div>
Attach a listener to the product-toggle class like so:
$(document).on('click', '.product-toggle', function() {
var target = this.dataset.target;
$('#'+target).toggle();
$(this).find('span.icon').toggleClass('icon-plus icon-minus');
});
JsFiddle
Note : Inline events are discouraged; you should use jQuery click handlers as you're already using jQuery.
For example (Demo):
$('a.product-toggle').click(function(e){
$(this).closest('p').next('div').toggle();
$(this).find('span.icon').toggleClass('icon-plus icon-minus')
})
If you need to use inline event calls,
You need to alter the second line to get the icon for current element
function toggleDiv(divId) {
$("#"+divId).toggle();
$("#"+divId).prev('p').find('.product-toggle span.icon').toggleClass('icon-plus icon-minus')
}
because,
$('.product-toggle span.icon')
selects all the <div>s
or pass this with the click event.
<p><a href="javascript:toggleDiv('features',this);"...
and
function toggleDiv(divId,currEl) {
$("#"+divId).toggle();
$(currEl).find('span.icon').toggleClass('icon-plus icon-minus')
}
Here is something I came up with which is a more handy solution and is not using javascript in href.
$('.product-toggle').on('click', function(evt){
// This will be set to the context of the current element
$("#"+this.name).toggle();
$(this).find('.icon').toggleClass('icon-plus icon-minus');
});
This requires that you give the a tags a name instead of calling the function directly. Here is a link to the fiddle: http://jsfiddle.net/ttpfzrgL/
Try this
function toggleDiv(divId) {
var idSelector = "#"+divId;
$(idSelector).toggle();
$('p').has('idSelector').closest('span.icon').toggleClass('icon-plus icon-minus');
}

Javascript " getParent() " not working

I have to hide my parent span just above <a> tag and show the span just below it.(When clicking it on the <a> tag).
I need to use getParent() because their are another same <div>s repeating
My HTML is
<div class="Test">
<p class="commentBody">
<span class="view_more-comment">abcd...
<a class="view_more_link" href="javascript:void(0);" onclick="$(this).getParent().getNext().style.display='';$(this).getParent().style.display='none';">more</a>
</span>
<span class="view_more" style="display: none;">abcdefghijklmnopqrstuvwzyz...
<a class="view_less_link" onclick="$(this).getParent().getPrevious().style.display='';$(this).getParent().style.display='none';">less</a>
</span>
</p>
</div>
When I use this console shows the error
Uncaught TypeError: $(...).getParent is not a function
Any method to solve this problem?.
There is no getParent() in jQuery. Use:
onclick="$(this).parent().prev().show(); $(this).parent().hide();"
Docs
Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
I'd recommend you to use on for event handling and not inline handlers
EDIT
Using jQuery:
$('.view_less_link').on('click', function() {
$(this).closest('.commentBody').find('.view_more-comment').show();
$(this).parent().hide();
});
Use .parent() instead of getParent().
Update your html as below and keep a similar class for both the links
DEMO
<span class="view_more-comment more">abcd...
<a class="view_link " href="javascript:void(0);">more</a>
</span>
<span class="view_more less" style="display: none;">abcdefghijklmnopqrstuvwzyz...
<a class="view_link" href="javascript:void(0);">less</a>
</span>
and then this JS
$('.view_link').on('click',function(){
$(this).parent().slideToggle(200);
$(this).parent().siblings().slideToggle(200);
});

How to get class with * in jQuery and CSS?

I have many elements:
<span class="test"></span>
<span class="aaa"></span>
<span class="test-one"></span>
<span class="test-two"></span>
<span class="aaa-one"></span>
<span class="test-two"></span>
How can i get with one select all span with name test*?
I can:
$('.test, .test-one, .test-two')
but maybe is possible to get this with regex?
$('.test*')
?
in css:
.test, .test-one, .test-two
.test*
You're abusing classes, and are looking for multiple classes instead:
<span class="test"></span>
<span class="aaa"></span>
<span class="test one"></span>
<span class="test two"></span>
<span class="aaa one"></span>
<span class="test two"></span>
Now, $('.one') will correctly return the 3rd and 5th element, and $('.test') will return all elements except the 2nd and 5th.
Note that you can also use $('.two.test') to get the 4th and 6th element.
Use the starts-with selector:
$('span[class^="test"]').
http://api.jquery.com/attribute-starts-with-selector/
It's not clear from the small example whether there's a pattern to the -one and -two class names.
If there is a pattern, and your idea is to have alternating classes (eg odd and even rows?), then you might want to consider using the nth-child() selector. This will allow you to select the relevant elements without needing to reference any class names at all.
In this case, you could do something like this:
<div class='container'>
<span class="test"></span>
<span class="test"></span>
<span class="aaa"></span>
<span class="test"></span>
</div>
and then the jquery:
$('container span:nth-child(odd)')
and
$('container span:nth-child(even)')
See the jQuery manual for nth-child for more info.
If this isn't what you're looking for, then I would suggest following #NielsKeurentjes advice and using multiple class names in the relevant elements.
Hope that helps.
I would change the classes, because a HTML-Tag can have multiple classes at once:
<span class="test"></span>
<span class="aaa"></span>
<span class="test testone"></span>
<span class="test testtwo"></span>
<span class="aaa-one"></span>
<span class="test testtwo"></span>
If you can't change the HTML, you can do it with javascript (jquery):
$('[class]').each(function(){
var className = $(this).attr("class");
if("test" == className.substring(0, 4)) //starts with "test"
{ doSomething();
}
});
(This code only works, if the tag has not more than one class)
But this is dirty code because it scans each dom-element which has a class.
If you only want to apply css-Style, the better solution, if you can't change the HTML, is to add all possible classes to the css-File:
.test, .test-one, .test-two{
...
}
...or using the css3-selectors as mentioned in the other answers, but older browsers won't support it.
You can use either
$("span[class*='test']"); // element with test anywhere in class attribute
or
$("span[class^='test']"); // element with test at the start in class attribute
note that these will work only if the element has single class.
however you should better use what #Niels have shown.
For a good CSS selector reference : Tutorial from net.tutsplus.com

Categories

Resources