Extracting values from Array with Javascript - javascript

I am having issues with getting exactly values with Javascript.
Following is working version of when we have class on single item.
http://jsfiddle.net/rtnNd/
Actually when code block has more items with same class (see this: http://jsfiddle.net/rtnNd/3), it picks up only the first item which use the class name.
My issue is that I would like to pick up only the last item which use the class name. So I used following code:
var item = $('.itemAnchor')[6];
var href = $($('.hidden_elem')[1].innerHTML.replace('<!--', '').replace('-->', '')).find(item).attr('href');
But it doesn't work though. I don't really know why.
The code that may contains items are using same class, class may be use in 2 items, 3 items, or 6th times. That's why, I want to pick up only the last item to extract.
Can you explain, thank you all for reading my question.

"My issue is that I would like to pick up only the last item which use the class name."
OK, so in a general sense you would use the .last() method:
var lastItem = $('.itemAnchor').last();
Except that there are no elements in the DOM with that class because (in your fiddles) they're all commented out. This is also the reason why the code you showed in your question didn't work. The first line:
var item = $('.itemAnchor')[6];
...sets the item variable to undefined. The selector '.itemAnchor' returns no elements, so $('.itemAnchor') is an empty jQuery object and it has no element at index 6.
You need to use the '.itemAnchor' selector on the html that you get after removing the opening and closing comments with your .replace() statements, so:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor').last().attr('href');
Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
"How can we pick up the itemElement before that last one."
If you know you always want the second-last item use .slice(-2,-1) instead of .last(), as shown here: http://jsfiddle.net/rtnNd/5/
Or if you know you want whichever one has an href that contains a parameter h= then you can use a selector like '.itemAnchor[href*="h="]' with .find(), in which case you don't need .last() or .slice():
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor[href*="h="]').attr('href');
Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the href has the text "h=" anywhere, so it works for your case but would also pick up hh=something or math=easy or whatever. You could avoid this and test for just h= as follows:
var href = $($('.hidden_elem')[0].innerHTML.replace('<!--','').replace('-->',''))
.find('.itemAnchor')
.filter(function() {
return /(\?|&)h=/.test(this.href);
}).attr('href');
Demo: http://jsfiddle.net/rtnNd/7/

Related

$("selector").find(":psuedo-class") does not return desired elements

I have the following declaration:
var optionsWithAttribute = $(element).find("option[data-attribute]");
I now want to grab the selected options from that set, so I write:
var selectedOptions = optionsWithAttribute.find(":selected");
However this yields the effective selector:
"option[data-attribute] :selected"
which obviously matches nothing (thanks to jquery.whiny for helping me to solve this). The correct selector would be:
"option[data-attribute]:selected"
(note lack of space after the ]).
Obviously this is because subsequent calls to .find() prepend a space so that (for example) the expression $("select").find("option") yields the selector select option as opposed to selectoption. Either I'm doing something wrong - in which case please educate me - or .find() should be changed to not insert a space if the passed-in selector is a pseudo-class (i.e. begins with a colon).
You need to use filter as optionsWithAttribute contains the option elements, find() will look for a matching descendant element
var selectedOptions = optionsWithAttribute.filter(":selected");
.find() selects children of the parent element , you need to use .filter() which will give you only the items with the select attribute
When you use this code var selectedOptions = optionsWithAttribute.find(":selected"); jquery will search all the elements with the attribute selected from the tag options (optionsWithAttribute)
try to use filter() method
Reduce the set of matched elements to those that match the selector or
pass the function's test.
var selectedOptions = optionsWithAttribute.filter(":selected");
"option[data-attribute] :selected"
which obviously matches nothing
Absolutely because that is incorrect, you can't find selected option inside options, so change it to:
var optionsWithAttribute = $(element).find("option[data-attribute]:selected");
console.log(optionsWithAttribute)

Use a Selector instead of "this" in Jquery

Maybe it's a silly question. But I really can't understand it.
I'm using the Jquery Cycle2. And after some personalization I got a simple problem.
I need to know what is the "Index" of my current slide.
On the plugin's website a found this line of code that perfectly works.
$('#cycle-1 .cycle-slide').click(function(){
var index = $('#cycle-1').data('cycle.API').getSlideIndex(this);
alert(index);
});
It gives me the right index. But I'm trying to catch this Index when another element is clicked. So I can't use the parameter (this).
Then I tried this.
$('.anotherelement').click(function(){
var mycycle = $('#cycle-1 .cycle-slide');
var index = $('#cycle-1').data('cycle.API').getSlideIndex($(mycycle));
alert(index);
});
It doesn't return my current slide index. It returns "-1". Does anyone knows how I should pass the Object (selector) as a parameter to the getSlideIndex() ?
Thanks a lot :D
You can use $('.cycle-slideshow').data('cycle.opts').currSlide to get the current slide index
$('.anotherelement').click(function(){
var index = $('.cycle-slideshow').data('cycle.opts').currSlide;
var currSliderNum = index+1;
alert(currSliderNum);
return false;
});
FIDDLE
In the first piece of code this is a DOM element and not a jquery object. Try this instead:
var index = $('#cycle-1').data('cycle.API').getSlideIndex(mycycle[0]);
However, presumably, you have multiple .cycle-slide elements. This will just get the first one. In your first code you have access to a single one since only one was clicked. You need to decide which one you want to target here.

Easy level, selecting elements in DOM, optimization, creating method function

Please, do not laugh, too much. I know jQuery ans JS for a short a while.
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
For the first one, why do you need a selector like that? couldn't you find something less specific to hook onto? If you must keep it when joining an number and a string, JavaScript will convert the number to string behind the scenes so you don't really need the .toString() and could do the "maths" +/-1 outside of your selector making it more readable.
Edit
In regards to your comment I am not really sure what you mean, you could assign a class to the "post" items and then add the unique id to a data-attribute ID. To make it simpler you could do something like this:
var codeLt = aktywneZdanie + 1,
codeGt = aktywneZdanie - 1;
$('code:lt(' + codeLt + '):gt(' + codeGt +')').removeClass('class2');
End Edit
And the second solution should work, all your doing is passing the dom elements found from your selector into a function as a jQuery "array" in which manipulate to your needs
And for your second question why not just toggle the class on and off? having a default state which reflects class one?
jQuery('#something').toggleClass('uberClass');
Or you can pass your selector to the function
changeClasses(jQuery('#something'));
Then inside you function work on the return elements.
Edit
Your code should work fine, but id suggest checking to make sure you have got and element to work on:
changeClasses(jQuery('#something'));
function changeClasses($element){
if($element.length > 0) {
$element.addClass('class1');
}
}
End Edit
Hope it helps,
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
I stoped creating this wierd code like this one above, instead I start using .slice() (do not forget to use .index() for arguments here), .prev(), .next(). Just those three and everything is faster and clearer. Just an example of it below. No it does not do anything logical.
var activeElem = jQuery('code:first');
var old Elem;
jQuery('code').slice('0',activeElem.index()).addClass('class1');
oldElem=activeElem;
activeElem=activeElem.next();
jQuery('code').slice(oldElem.index(),activeElem.index()).addClass('class1');
oldElem.toggleClass('class1');
activeElem.prev().toggleClass('class1');
and the second part
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
This one is still unsolved by me.

innerHTML to return a filtered syntax name of all the class with one name

im using this code to return the attrb name of the class tooltip (have more than one class in all the page)
CODE:
var hrefs = document.getElementsByClassName('tooltip_sticky');
for (var i = 0; i < hrefs.length; ++i) {
var item = hrefs[i].innerHTML;
}
alert(item);
HTML:
(http://i.stack.imgur.com/klS0N.png)
but it only return the <span.... of the last tooltip_sticky class, but i dont want this, i want to get the hrefs that have MISSION=1, i know its a matter of filter, but i cant first get the list of hrefs(i used another code that was getting the href outside the name="..", but the href inside, no...
im planning to get automatically all the hrefs that have mission=1 in the page, and open each one in another window automatically, its for a chrome extension!!
if someone can help me please, while this i will read about innerHTML getattribute
You are doing an alert() outside the loop so of course you only get the last one. In a statically scoped programming language, something like this wouldn't even compile because item is introduced inside the loop and used outside it.

Change href value using jQuery

How do I rewrite an href value, using jQuery?
I have links with a default city
parks
malls
If the user enters a value into a #city textbox I want to replace Paris with the user-entered value.
So far I have
var newCity = $("#city").val();
Given you have unique href values (?what=parks, and ?what=malls) I would suggest not writing a path into the $.attr() method; you would have to have one call to $.attr() for each unique href, and that would grow to be very redundant, very quickly - not to mention difficult to manage.
Below I'm making one call to $.attr() and using a function to replace only the &city= portion with the new city. The good thing about this method is that these 5 lines of code can update hundreds of links without destroying the rest of the href values on each link.
$("#city").change(function(o){
$("a.malls").attr('href', function(i,a){
return a.replace( /(city=)[a-z]+/ig, '$1'+o.target.value );
});
});
One thing you may want to watch out for would be spaces, and casing. You could convert everything to lower case using the .toLowerCase() JavaScript method, and you can replace the spaces with another call to .replace() as I've down below:
'$1'+o.target.value.replace(/\s+/, '');
Online Demo: http://jsbin.com/ohejez/
$('a').attr("href", "/search/?what=parks&city=" + newCity);
As soon as a key is released within the #city input field, the href will be updated.
$('#city').keyup(function(){
$('a').attr('href','/search/?what=parks&city='+$(this).val());
});
Like this:
var newCity = $("#city").val();
$('a').attr('href', '/search/?what=parks&city=' + newCity);
EDIT: Added the search string

Categories