jQuery .get()


The get() method is used to retrieve the elements specified by the selector. Let us say you have a 10 paragraphs of html in a webpage enclosed beteween the <p> and <</p> tags. Now you wish to access the content of the fifth paragraph. You could use the get method something like

$("p").get(4); Notice that the get(5) will access you the 6th paragraph. The parameter inside get is optional.

Let us take a look at the example


<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<!--
Referencedesigner.com jQuery Tutorial showing usage of .get()
-->

<script>
$(document).ready(function(){
  $("button").click(function(){   
    x=$("p").get(0); // Change get(0) to get(1) or get(2) and what happens
    $("div").text(x.innerHTML);
  });
});
</script>
</head>
<body>
<p>This is a Line 1</p>
<p>This is a Line 2</p>
<p>This is a Line 3</p>
<button>Click me to see action </button>
<div></div>
</body>
</html>




You may like to make changes in the index in the above example to see the effects.

You may like to try this example here.

If you do not specify it, you get all of the 10 paragraphs ( of course, we are referring to the example above). But there is a catch - it returns the elements in an array. So you will have to process it like an element.


Let us take a look at the example


<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<!--
Referencedesigner.com jQuery Tutorial showing usage of .get() without index
-->

<script>
$(document).ready(function(){
  $("button").click(function(){
    var x = [];   
    x=$("p").get(); // without a parameter get() returns an array
  
    $("div").text(x[0].innerHTML + x[1].innerHTML);
  });
});
</script>
</head>
<body>
<p>This is a Line 1</p>
<p>This is a Line 2</p>
<p>This is a Line 3</p>
<button>Click me to see action </button>
<div></div>
</body>
</html>




You may like to try this example here.