Question

I have this markup as shown below:

<div id="content_area">
<table width="100%" cellspacing="0" cellpadding="0" border="0" align="center">
<tbody>
  <tr>
    <td width="100%" valign="top">
      <div id="some_id"> </div>
    </td>
  </tr>
   </tbody>
</table>
</div>

Now i want to get the div with the id "content_area" using the div with the id "some_id" and style the "content_area" using jquery. How can i traverse upwars using ".parent() in this scenario? Will the table structure be a hurdle?

Was it helpful?

Solution

jQuery API closest

.closest( selector ) Returns: jQuery

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

OTHER TIPS

The ids are unique. If they aren't, change that to class.

If they are:

$('#content_area').css();

If you change that to class:

$('#some_id').parent('.content_area').css();

jQuery.parent()

$("#some_id").parent();

Will return the element <td width="100%" valign="top">


jQuery.parents()

$("#some_id").parents("#content_area");

Will return the element <div id="content_area">


jQuery.css()

$("#some_id").parents("#content_area").css({ color: "#333", height: "100%" });

Will style the element <div id="content_area"> with a font color of #333333 and a height of 100% of it's parent.

Pretty sure it's as simple as

$("#some_id").parent().parent().parent().css("some-style", "value");

Not sure why you wouldn't want to just do this though:

$("#content_area").css("some-style", "value");

If it's because you have multiple divs with the same ID, consider switching to using classes. Each ID should only occur once on any given page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top