Target first and second occurrence of Div on page using Jquery - javascript

Hi I am trying to target the first and second occurrence of a div class on a page, I have the following but this does not work?
var first = ($("#area").find(".cArea")[0]);
var second = ($("aArea").find(".cArea")[1]);
Any ideas?

You can use the :lt() selector to achieve this. It selects the elements in a collection whose index is lower than a provided value.
var $firstAndSecond = $('#area .cArea:lt(2)');

You can use the :eq(index) selector to get directly the first and second one.
var first = ($("#area").find(".cArea:eq(0)"));
var second = ($("aArea").find(".cArea:eq(1)"));

Related

how to get second last element using java script

I have a drop down of 7 options. I need to get the value of second last option using java script. I wrote something but it is not working .
$('.checkbox4').on('click', function(e) {
var last_chekbox4 = $('.checkbox4:last.prev()');
if (last_chekbox4.is(':checked')) {
$('.checkbox4').prop('checked', false);
$(this).prop('checked', true);
}
});
Use prev() method
$('.checkbox4:last').prev()
If there is some other element in between then use
$('.checkbox4:last').prevAll('.checkbox4').first()
FYI : Above methods don't work if elements are not siblings.
UPDATE :
Or get the last within the collection which excluded the last one using :not() and jQuery :last.
$('.checkbox4:not(:last):last')
Or by the index using eq() method.
var $col = $('.checkbox4');
// get element by index, where index starts from 0
var $ele = $col.eq($col.length - 2);
You have 7 elements. Use nth-of-type selector
$(".checkbox4:nth-of-type(6)");
To select the second last option

In jQuery, what is the difference between `this.element` and `this.element[/* some number */]`?

I came across the following in a piece of code:
var searchBox = $(this.element[0]);
I'm pretty new to Javascript and jQuery. I am trying to understand it but i am having a hard time. This line is in an implementation of jQuery UI Accordion widget.
What does the this refer to?
Also, I played a bit with the line and I came to an understanding that it works perfectly - no matter what number is in the array. In addition, if I remove the brackets and just write the following line, it works just fine:
var searchBox = $(this.element);
What is it means and what is the difference?
Thank you very much. :)
Edit:
Here is my full code. Maybe it could help. https://jsfiddle.net/yx8puo2j/1/
var searchBox = $(this.element[0]);
returns one element (1 object).
var searchBox = $(this.element);
return a list of elements.
This states for classes, not for id (cause id is unique).
Examples:
var searchbox = $(this.angry_button) returns all (list) elements with class angry_button.
var searchbox = $(this.angry_button[0]) returns the first element with class angry_button.
var searchbox = $(this.angry_button[1]) returns the second element with class angry_button.
When you use
var searchBox = $(this.element[0]);
You're selecting the first
element
of "This" where "This" is the element you're currently in like a div or an input field
I cant tell you what this is, but I can explain a bit what happens and why it works:
In jQuery you can select any element with $(""), but what if you select an class that exists multiple times in the DOM??
So I got this button class that exists 5 times in the document and i select it with $(".button") . This now returns an array with 5 items in it.
If we want to select the first button that would be $(".button[0]") if we want to select the fifth button that would be $(".button[4]")
so basically you are selecting element n within the page that has that specific identifier.

jQuery select dropdown value based on value of other dropdown

I'm trying to get my head around jQuery, but I have trouble figuring out plain arrays vs jQuery arrays, and DOM elements vs jQuery elements.
So here's an example I try to do. The example is simple really, but I need some hand-holding :-p so I'll be verbose in my requirements hoping that the answers will be, in turn, descriptive.
I have two <select> drop-downs, with IDs #version and #target.
When I click a button, I want to select in #target the option following with the same name as the last-but-one value in #version. (the item WILL exist)
Example: #version has options: a,b,c,x. #target has options a,b,c,d,h,m.
I click the button. What should happen is:
read the last-but-one option in #version: "c"
find the option with the same name in #target: the 3rd (i.e. index is 2)
set the selected value in #target to the one after "c", i.e. "d" (the 4th, index 3)
Here's a fiddle with the example.
For the 1st step, I think I figured it out:
var latestVersion = $("#version option").get(-2).text;
//side-note: why does .text work but not .val() ? oh, .get() returns a DOM element
// so How do I get back to a jQuery element?
// $($("#version option").get(-2)).val() works but looks ugly
For step 2, I tried this:
var target = $("#target option:contains(latestVersion)");
but it doesn't work. And there's GOT to be a better way than manually iterating all the values searching for the right one.
Step 3: ??.
Using 1st step as you figured try the following:
$('#button').click(function(){
var latestVersion = $("#version option").get(-2).text;
//index of LAST-BUT-ONE
var target=$("#target option[value="+latestVersion+"]").index();
//Setting next index value
$("#target").prop("selectedIndex",target + 1);
});
http://jsfiddle.net/GpBDY/16/
.val() does not work on an option element, but it does work on a select element:
var v = $( "#version" ).val();
gives you the element selected in the dropdown #version.
The following line will not do what you want:
var target = $("#target option:contains(latestVersion)");
That is because latestVersion is treated as the value "latestValue" and not as the name of a variable. To use the value of the variable latestValue, put latestValue outside the string like:
... contains(" + latestVersion + ")...
You might be interested in the jQuery method .next() in combination with your code in step 2 to get the value of the next option element. Be aware that if there is no next element, the value will be "undefined".
You can do this using nth-child to select value of version and using that set the value of target this way:
$('#button').click(function(){
var latestVersion = $("#version option:nth-child(3)").text();
$("#target").val($('#target option[value="'+latestVersion+'"]').next().text());
});
Demo Fiddle
i am not sure i understand you are looking for, but i think that you want something like this:
$('#button').click(function(){
var arrVersion = $("#version option");
var latestVersion = $(arrVersion[arrVersion.length - 2]).val();
$("#target").val(latestVersion);
var actualSelected = parseInt($("#target").prop("selectedIndex"));
$("#target").prop("selectedIndex", actualSelected + 1);
});
http://jsfiddle.net/GpBDY/9/

Selecting a last child in javascript

I have a handle on an Un-ordered List (for my example i will call the handle Var1) and would like to be able to assign its last li to a variable. I tried Lastli = var1.lastChild the only method I figured would work but it didn't. I can't seem to find a answer to this using only Javascript not jQuery any help is appreciated.
You can select the parent element and use the lastChild property.
var container = document.getElementsByTagName("ul")[0];
var lastchild = container.lastChild;
Or you select all the items into an array and get the last item. Here is a quick example:
var items = document.querySelectorAll("li");
var lastchild = items[items.length-1];
you can select all 'li' and take the last one. Something like:
var myLi = document.getElementsByTagName('li');
var lastLi = myLi[myLi.length-1];
Lets consider an example
<ul >
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
To get the last child of the list you can simply make use of queryselector
document.querySelector('li:last-child'); //this will return Milk which is the last child of the list
document.querySelector('li:first-child') OR document.querySelector('li'); //both will give you the first child of the list
Suppose you want the n-th child for that you can use the following syntax:
document.querySelector('li:nth-child(2)'); //it will return the second child (here Tea)
If you want all the list item in the given list:
document.getElementsByTagName('li') //(Will return the whole list)here i am using tagname. It can be also applied on classname or element id
Try this: .childNodes[childNodes.length - 1]
either ulReference.children[ulReference.children.length -1] or ulReference.childNodes[ulReference.childNodes.length -1]. The difference between the two can be found here
The simplest way is to use the document.querySelector and use the :last-child to get it.
Exemple:
const list = document.querySelector("li:last-child");

Select Element From List by Index with jQuery

<form id="foo">
<input></input>
<input></input>
<input></input>
</form>
I want to do:
document.getElementById("foo").getElementsByTag("input")[1];
But in jQuery. I want to select a certain object under #foo by an index.
This is my first guess as to how to do this:
$('#foo input[1]').val("BlahBlah");
I think it would be the same in CSS too.
You could do it this way:
$('#foo input').eq(1).val("BlahBlah");
That will give you the second input. If you want the first, change the 1 to a 0. The .eq() function is 0 based.
In jQuery there are a couple of methods defined to select and use elements from a (DOM objects) list.
By using:
var list = $("#foo");
You would capture the entire #foo. If your in for simplicity you could get the children (i.e the input fields) by using var children = list.children(); But if you want something that seems a bit more like findElementsByTag, you could use var children = list.find('input'); (Which ofcourse could be a one liner, but usually you want to re-use the entire list too)
To get the first and last item of a certain list of children there are some predefined functions:
var first = children.first();
var last = children.last();
To find an -nth element you can use http://api.jquery.com/eq/ or http://api.jquery.com/nth-child-selector/
So you would get (note it works just like an array with 0-based index)
var second = children.eq(1);
If you like CSS selector style more you can also try (note the 1-based index)
var second_b = $("#foo input:nth-child(2)");
$('#foo :input').eq(1).val('BlahBlah')
You can use the eq() selector:
$('#foo input:eq(1)').val("BlahBlah");
You can use the eq selector. It receives a zero-based index:
$('#foo input:eq(1)').val('a value');
Use nth-child(n) pseudo class like this ...
$("#foo input:nth-child(0)").val("BlahBlah");
$("#foo input:nth-child(1)").val("BlahBlah");
.
.
.
$("#foo input:nth-child(n)").val("BlahBlah");
I'll say :
$($('#foo input')[1]).val("BlahBlah");

Categories

Resources