tags:

views:

56

answers:

3

I have an ASP.NET server control which produces html. I have no control on the html produced. However I need to style some elements in the html using jQuery. I need to style the div shown below which has no class or id. The first child element which has an id is the Select element which has an id=mySelectID. How do I reference the div element using jQuery?

.......
<div style="height:30px;">
    <table cellpadding="0" cellspacing="0">
        <tr>
                <td height="15px"><select id="mySelectID" ....
.......
A: 

Traverse up from the select:

$('#mySelectID').parent().parent().parent().parent()
casablanca
casablanca - Actually, this will not always work. Some (but not necessarily all) browsers insert a `<tbody>` element when it is missing, so chaining `.parent()` calls may give inconsistent results. If it wasn't for the `<tbody>` issue, your solution would be fine. :o)
patrick dw
+5  A: 

You can use the parents() selector for this.

$('#mySelectID').parents('div:first');

This will return the first parent which is a div.

BalusC
This is your answer.
Andir
@Andir - Why is that? (No offense BalusC. I just get a kick out of these self-appointed referees.)
patrick dw
@patrick: Because it works and it's clear in intent?closest() "works" here too, but it can be confusing to the casual reader in the jQuery devs choice of method names. If I were glancing at the code and someone put a div just inside the td, the closest div is the child at that point (even if jquery looks through ancestors) and a developer further down the line may read it and think the logic is all wrong. Explicitly stating you want the first div in the parents is very clear intent. closest() is not.(I just get a kick out of these self-appointed antagonists!)
Andir
@Andir - So you decided that this is the OP's answer because you don't like the method name, "closest". Fine. At least that is a little better than your unhelpful statement *"This is your answer."*. You are the antagonist when you steer the OP away from valid answers without offering good reason.
patrick dw
Holy crap, you are right! I've finally reached a new ultimate efficiency score for antagonism! Who knew those four little words would have been my crowning achievement in my lifelong quest to become a super-villain named: The Antagonizer! I should get a cape... wait! I HAVE to share this skill with the world. I should go on tour and spread my powers of efficient antagonism! People will speak of this post for years to come! Come my minions! Let's be off!
Andir
@Andir - Wow, *"...a super-villain named: The Antagonizer!"*? I'm only saying that if you feel the need to steer the OP toward a solution, give an intelligent reason as to why. It promotes discussion. Otherwise you're just acting as a self-appointed referee.
patrick dw
+1  A: 

Use closest().

$('#mySelectID').closest('div')
Ken Redler