开发者

jquery select Table, but only after Div

On most my pages I have a specific div that holds the title for that page:

<div id="pagetitle">Some Title</div>

And usually immediately after is a table. I want to select all tables, but only tables after the #pagetitle div.

I intend to add some css to just those tables. Currently I am having to create a class and add that class to all the tables. But I have tons of pages.

Current code:

$('table.valigntop tr td').css('vertical-align','middle');
开发者_开发百科

I need a little help with creating a cool jquery select statement that selects all tables that exist after the #pagetitle element. Whether it's the best way for my sites is still to be determined.


Alternatively, you can also use nextAll() Here's an example http://jsfiddle.net/Q8Af6/

HTML:

<table><tr><td>table one</td></tr></table>
<table><tr><td>table two</td></tr></table>
<div id='pagetitle'></div>
<table><tr><td>table three</td></tr></table>
<table><tr><td>table four</td></tr></table>
<table><tr><td>table five</td></tr></table>

CSS:

div, table{
    display:block;
}

JS:

$('#pagetitle').nextAll('table').css("background", "yellow");

EDIT JS: Add the td selector http://jsfiddle.net/Q8Af6/1/

$('#pagetitle').nextAll('table').find('td').css("background", "yellow");


Select the tables like this:

$("#pagetitle ~ table")


Most efficient fix would be to actually put those tables inside a container, and then you can just modify the tables inside that container.

A simple div with no css at all (except reset styles) would do.


When you say "immediately after" it sounds like you mean "the table is at the same DOM level as the div -- in other words, it's a sibling of the div." Is that right?

If so, you can use the jQuery Next Siblings Selector. Something like this:

$('#pagetitle ~ table.valigntop tr td').css('vertical-align','middle');

Or see the examples at http://api.jquery.com/next-siblings-selector/, which should also get you what you want.

Edit

The more I look at the first version I posted, I realize that it is really looking for the td which is a sibling of #pagetitle, not the table which is a sibling of #pagetitle.

That means the correct way to accomplish this is to first select the tables using the sibling operator, then find those tables' children, more like this (http://jsfiddle.net/T3nuQ/6/):

$("#pagetitle ~ table").find('tr td').css('vertical-align','middle');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜