I have just started using jQuery and although following code gets the job done, I have a feeling that it can be shortened.

var accountAddress = $(document.createElement("input")).addClass("readOnly")
        .attr("contentEditable", "false").attr("id", "d_accountAddress");


If it is not clear - what I'm doing is creating new input tag, assigning class and making it read-only, then positioning new input two TD's to the right of some known text.


This is simplified HTML that I'm modifying. The place where I add content is marked with ##1## and ##2##.

<TD id=customerid_c>
    <LABEL for=customerid>Customer</LABEL>
<TD id=customerid_d></TD>
<TD class=ms-crm-Field-Normal>
Ted Goas
  • 7,051
  • 1
  • 35
  • 42
David Vidmar
  • 3,042
  • 6
  • 29
  • 35

1 Answers1


Yes, it can.

    .append('<input class="readOnly" id="d_accountAddress" />');

In jQuery 1.4.2, you can write

    .append('<input class="readOnly" id="d_accountAddress" />');

This selector, which does not work correctly in earlier versions of jQuery, uses the Next Siblings Selector (~) to select all sibling elements following #customerid_c, then uses the :eq selector to select the third (zero-based) element matched by the other selector.

jQuery has a large variety of selectors that can probably replace the indexed sibling. If you show us your HTML, we can find you one.

Other notes:

You can set multiple attributes in one call:

$(something).attr({ id: 'd_accountAddress', type: 'text' });
  • 1
  • 1
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    I've never seen that syntax before, what does `#el~:eq(2)` specifically do? – Tatu Ulmanen Mar 22 '10 at 12:54
  • I think that the ~ is used to navigate to the children of an element, in this case #customerid_c, and eq is the equality operator, in this case used to go to the 0 based index, so the third child. – Kieron Mar 22 '10 at 12:57
  • 6
    A cleaner way to write it would be. $('#customerid_c').nextAll().eq(2).append(''); – PetersenDidIt Mar 22 '10 at 13:03
  • @Tatu, @used, @Kieron, @mmcgrail: That selector does work in 1.4.2. SO uses 1.3.2, which apparently has a bug. – SLaks Mar 22 '10 at 13:25
  • @Kieron > is child elements, ~ is siblings – Ed James Mar 22 '10 at 14:03
  • @petersendidit - please post this as an answer, for the googler's sake. – user187291 Mar 22 '10 at 15:20
  • @SLaks i might open a new thread but i have a query related to selectors itself. Please answer or give me a link to answer. I want to know how can we select Elements of ASP.Net Auto Generated IDs. i know i can check for the endwith myID but then in grids or list items they are same. so how to do it a cleaner way... – Shekhar_Pro Jan 18 '11 at 04:24
  • 2
    @Shekhar: You can't. (Unless you hard-code the full ID, perhaps using server-side inline code) – SLaks Jan 18 '11 at 04:26
  • oh! i was expecting for some workaround in jQuery itself... thanx for your time.. – Shekhar_Pro Jan 18 '11 at 04:36