Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a single element in jQuery?

I have a table structure that looks like:

<table>  <tr id="row1">    <td>      <div>row 1 content1</div>    </td>    <td>      <div>row 1 content2</div>    </td>    <td>      <div>row 1 content3</div>    </td>  </tr>  <tr id="row2">    <td>      <div>row 2 content1</div>    </td>    <td>      <div>row 2 content2</div>    </td>    <td>      <div>row 2 content3</div>    </td>  </tr>  <tr id="row3">    <td>      <div>row 3 content1</div>    </td>    <td>      <div>row 3 content2</div>    </td>    <td>      <div>row 3 content3</div>    </td>  </tr> </table> 

Using jQuery I am trying to select the DIV in the second cell of the third row. I tried the following (amongst other things):

var d = $('#row3').children(':eq(1)').children(':eq(0)'); 

What I get back is an array with a single element (the DIV I'm after) and I have to then access using d[0]. Why is jQuery returning a single element array, I thought using the selector above would return the DIV element directly?


@Shog9 - Duh...Ok a light just switched on in my brain, I get it now. Cheers.

like image 994
Kev Avatar asked Nov 21 '08 01:11

Kev


People also ask

How do you select a specific element?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

What does the selector $( div select?

The $() factory function Every jQuery selector start with thiis sign $(). This sign is known as the factory function. It uses the three basic building blocks while selecting an element in a given document.


2 Answers

If you prefer keeping a jQuery object, you may write instead:

$("selector").first().val() 
like image 72
vcarel Avatar answered Sep 29 '22 13:09

vcarel


jQuery always returns a set of elements. Sometimes, the set is empty. Sometimes, it contains only one element. The beauty of this is that you can write code to work the same way regardless of how many elements are matched:

$("selector").each(function() {    this.style.backgroundColor = "red"; }); 

Fun!

like image 24
Shog9 Avatar answered Sep 29 '22 14:09

Shog9