开发者

How do I use jQuery to select this div and change the html?

I have the following html:

<div class="scroller-pane">
    <div class="scroller-header"></div>
    <div class="scroller-division" id="0">
        <div style="height:20px;"></div>
        <div class="title">A day with bears</div>
        <div class="date">30/06/2011</div>
        <div class="clear"></div>
        <div class="text">Lorem Ipsum is simply dummy text of the printing...</div>
    开发者_开发知识库    <div style="float:right;"><a href="htp://www.google.com">more>></a></div>
    </div>
<div>

And I have called:

console.log($('.scroller-pane .scroller-division #0 .title').html());

and

console.log($('.scroller-pane > .scroller-division > #0 > .title').html());

But all I get is 'undefined', why have neither of these select statement not worked? How do I write a jQuery select statement to get to the 'title' div..?


If you have the ID of the element, just target it by that:

console.log($('#0').children('div.title').html());


you can just access it via the id, using $('#id') however I think that it's not allowed to have a number as the first character of an id


console.log($('.scroller-pane .scroller-division#0 .title').html());


And I have called:

console.log($('.scroller-pane .scroller-division #0 .title').html());

That says "Find all elements with class "title" that are descendants of an element with the id "0" that's a descendant of an element with the class "scroller-division" which is a descendant of an element with class "scroller-pane". But your element with id "0" is the "scroller-division", it's not a descendant of it.

If you really want to target this only if the element with id "0" is nested in that way, and to do nothing otherwise, you'd do this:

console.log($('.scroller-pane .scroller-division .title').html());

or

console.log($('.scroller-pane #0 .title').html());

or

console.log($('.scroller-pane .scroller-division[id=0] .title').html());

(That last will ignore elements with id "0" if they don't have the class "scroller-division".)

But if you want to target the "title" descendants of id "0" regardless of where it is, it gets a lot shorter:

console.log($('#0 .title').html());

Off-topic: Strongly recommend you don't use "0" as an id value. It's valid in HTML5, but it's invalid in HTML4.01 and earlier (ids can't start with a digit), and it's invalid in CSS (same).


I'm not sure if you want to change the html or retrieve it, but here's examples of both:

http://jsfiddle.net/wUV5r/

$(document).ready(function() {
    alert($('.scroller-pane .scroller-division[id=0] .title').html());
    $('.scroller-pane .scroller-division[id=0] .title').html('test');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜