JQuery Newest Novice: Using Selectors, Can I select the second P tag within a list?

Hello everyone:
I reading some really exciting stuff on JQuery and started to skip pages but can’t find what I am looking for regarding Selectors.
I have an Un-Ordered List like this:

<ul>

<li>
<p>First Paragraph</p>
</li>

<li>
<p>Second Paragraph</p>
</li>

</ul>

I want to use classes at a minimum because I already have an ID on the P tag for ASP.

How do I select the second tag exclusively? I could filter by value or content but all the P tags in the list have similar stuff. I also see that I can use the contains() to find the tag based on specifics; but are there other ways to simply select the tag based on it’s position?

Thanks for your help.

IC

You haven’t shown this in your example, but if you’re saying that each P element inside the list has an id, then it would be simplest to select using that, e.g. $("#my-p-id");

If you don’t have ids that you can select on, you could do something like this: $("li p")[1]; which will select all the paragraphs inside li tags, and give you the second match.

Although it’s good to avoid over-using classes and ids by putting them on every other element in the page, don’t hold back from using them where it’s going to simplify your jQuery selectors.

To elaborate on what fretburner says, $("li p")[1] will indeed select all the paragraphs inside li tags, and give you the second match.

However, it will also return a DOM Node, as opposed to the .eq() method which will return a jQuery object (which is useful for chaining).

E.g.

$('li p').eq(1).css('background-color', 'red');

=> Turns the background red.

$('li p')[1].css('background-color', 'red');

=> No effect.

Both have their uses, depending on what it is you are trying to achieve.

http://api.jquery.com/eq/

Here are a few more selectors:

$("ul > li:eq(1) > p")  //:eq is 0 based
$("ul > li > p").eq(1)    //jquery docs recommend eq() over :eq
$("ul > li:nth-child(2) > p")   //:nth-child is 1 based

Thanks everyone for responding, I really appreciate your help.

The page is an ASP page: So I already have an ID doing things for the Server. So if I put JQuery via the ID, I risk causing a conflict between what the Server is doing on the Tag verses what I need JQuery to do.

But you all make a valid point and I think I should look more into how I can make both Systems use the same tag if at all possible. Maybe there is a way.

Either way, based on your responses I jave more options to move along and see what the best approach is.

Thanks again my friends.

P.S. How do I mark a thread or question as answered?

IC

I risk causing a conflict between what the Server is doing on the Tag verses what I need JQuery to do.

I don’t know anything about ASP, but I’ll still say, “That’s impossible.”

Hi there,

I don’t see any reason that this would not be possible as jQuery and ASP are two completely unrelated technologies.

You can’t, I’m afraid.
I asked the same thing a while back. The rationale is that it’s always possible that someone with a better answer turns up and adds to the discussion.

It is not impossible but it depends on your project: There are hundreds of books that will tell you the pain it can take to do some simple things. Inf act, this is the biggest selling points of MVC as it outputs pure HTML and sits very well with JQuery.

Just out of interest, could you give us an example of what you mean.

Sure, no problem:

The following code is a section of my primary form: I find it better to put all of my form elements in a list, this way I can align or place them in precise position as if they were in a table:


   <fieldset id="contact">
    <legend class="category">Contact Information</legend>
    <ul>
     <li>
      <p runat="server" id="dupEmailError">
       <i>Email Address Already Registered:</i>
       Forget your login? Recover your username or reset password
      </p>

      <p class="default" runat="server" id="emailError">
       <i>Invalid Email Address:</i>
       Max lenght 20, cannot start with dash or underscore:
      </p>
      <asp:TextBox ID="txtEmail" runat="server" TabIndex="7" MaxLength="50"></asp:TextBox>
      <label runat="server" id="lblEmail" for="txtEmail">* Email</label>
     </li>

     <li>
      <p class="default" runat="server" id="emailConfirmError">
       <i>Please Confirm Email:</i>
       Both email address entered must match.
      </p>
      <asp:TextBox ID="txtConfirmEmail" runat="server" TabIndex="8" MaxLength="50"></asp:TextBox>
      <label runat="server" id="lblConfirmEmail" for="txtConfirmEmail">* Confirm Email</label>
     </li>
    </ul>
   </fieldset>

Originally the idea was, when the page loads, the error is hidden, not by CSS but on the Server, because I did not have JQuery at the time: All I did was:

[highlight=“C#”]
protected void Page_Load(object sender, EventArgs e)
{
//hide all error message on page load
}




If you look at the code: I am using HTML tags but adding the Server Attribute which allows me to hide the error messages:  

Runat=“Server”


Why did I do this? Because ASP.NET labels are a bunch of <span> tags.

[highlight="C#"]
      <p runat="server" id="dupEmailError">
       <i>Email Address Already Registered:</i>
       Forget your login? Recover your username or reset password
      </p>

      <p class="default" runat="server" id="emailError">
       <i>Invalid Email Address:</i>
       Max lenght 20, cannot start with dash or underscore:
      </p>

      <p class="default" runat="server" id="emailConfirmError">
       <i>Please Confirm Email:</i>
       Both email address entered must match.
      </p>

Something like this:
[highlight=“C#”]
<asp:Label ID=“Label1” runat=“server” Text=“Whats your name”></asp:Label>



[I][B]
Will look like this after it is rendered by the server:[/B][/I]

<span>What is your name</span>



I decided to use paragraph tags and control them from the server by adding the server attribute and an ID.

Another thing I did for the sake of [I][B]performance[/B][/I] is to remove the ID of any tags that is not used immediately by the server: 

[B][I]Something like this:[/I][/B]
[highlight="C#"]
<asp:Label ID="lblThisIsMyId" runat="server" Text="Whats your name"></asp:Label>

Will look like this:


<span>Whats your name"></span>

This may not same like much but it reduces ViewState and provides a more cleaner HTML. Especially for pages where there are hundreds of tags with ID.

Now how does this affect JQuery? It doesn’t, however it does affect my approach and design.
The problems I had is that when ASP.NET is using a specific tag, then I have to work around it so that JQuery has access to the same tags.

Example: I can no-longer hide the ID’s. But the biggest hurdle is with the error messages. If the server is hiding the error messages on Load, then JQuery cannot access those tags. So instead of hiding the error messages on the server,
I simply had to add the CSS dynamically by the server. But to do this I still need an ID on the p tags because that’s the only way the server can interact with them (I do not know another way).

So the code looks like this:

[highlight=“C#”]
userNameError.Attributes[“class”] = (Validated.IsValidUsername ? “default” : “error”);
txtUserName.CssClass = (Validated.IsValidUsername ? “” : “alert”);
lblUserName.ID = (Validated.IsValidUsername ? “” : “lblUserName”);



[I]
This line removes the ID if the tag is not in use of if there are no error messages:[/I]

[highlight="C#"]
 lblUserName.ID = (Validated.IsValidUsername ? "" : "lblUserName");

The result of all of this is that I have a cleaner more usable HTML.

I am not saying ASP.NET does not work with JQuery, I am saying ASP.NET is not like PHP where tags can love each other side by side. ASP.NET needs an ID for everything and if those ID are doing other things, you may need to add JQuery directly to the tags or add a class.

Lastly, the plan to switch to ASP.NET MVC which is more cleaner, I am a purist I hate a page fill with bunch of span tags. I also cannot stand anything dynamic generated (html). With MVC you write your own HTML, so nothing is really generated. You have control of what tags goes where.

Thanks again!

Hi there,

Thanks for taking the time to reply.
I think we are talking about slightly different things.
I thought you meant that by including a class or id attribute on a tag (e.g. <span class=“whatever”>), you could cause some kind of conflict between ASP and jQuery.
However, having read your reply, this does not seem to be the case.