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.
OK, so in a general sense you would use the
.last()method: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:
…sets the
itemvariable toundefined. The selector'.itemAnchor'returns no elements, so$('.itemAnchor')is an empty jQuery object and it has no element at index6.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:Demo: http://jsfiddle.net/rtnNd/4/
EDIT in response to comment:
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
hrefthat contains a parameterh=then you can use a selector like'.itemAnchor[href*="h="]'with.find(), in which case you don’t need.last()or.slice():Demo: http://jsfiddle.net/rtnNd/6/
Note though that this last method using the attribute-contains selector is picking up elements where the
hrefhas the text “h=” anywhere, so it works for your case but would also pick uphh=somethingormath=easyor whatever. You could avoid this and test for justh=as follows:Demo: http://jsfiddle.net/rtnNd/7/