0

If I have the following HTML

<div class="main">
    <div class="header">

    </div>
    <div class="sub_header">
        <input type="text" class="txtBox" />
    </div>
    <div class="content">

    </div>
    <div class="footer">

    </div>
</div>

Using txtBox as a starting point, how do I find the closest content so I can add something to it?

Here if the full script I have at the moment:

$(document).ready(function() {
    var myDate = new Date();
    var todaysDate = myDate.getDate() + '/' + (myDate.getMonth()+1) + '/' + myDate.getFullYear();

    get_data( todaysDate );

    $(".txtBox").val(todaysDate).datepicker( {
        changeMonth: true,
        changeYear: true,
        yearRange: "+0:+1",
        showButtonPanel: false,
        dateFormat: "d/mm/yy",
        onSelect: function(dateText, obj){
            get_data( $(this), dateText );
        }
    } );

    function get_data( that, dateText ) {

        if ( typeof that != "undefined" )
        {
            that.closest('.main').find('.content').empty().append( dateText );
        }
        else
        {
            $(".content.new").append( dateText ).removeClass('new');
        }

    }

});
1
  • Updated question with current full script. Commented Nov 2, 2012 at 10:01

4 Answers 4

2

jsBin demo

$('.txtBox').closest('.main').find('.content').text('Hello oshirowanen!');

or:

$('.txtBox').closest('div').next('.content').text('Hello oshirowanen!');

or:

$('.txtBox').parent().next('.content').text('Hello oshirowanen!');
4
  • Using your middle example gives the following error Object doesn't support this property or method. The line giving the error looks like this: that.closest('.main').find('.content').empty().append( dateText ); where that is .txtBox. Not sure what I am doing wrong? Commented Nov 2, 2012 at 9:58
  • Updated question with current full script. Commented Nov 2, 2012 at 10:02
  • For some reason, I can't get your jsbin example to work with the script I have in my original question. Commented Nov 2, 2012 at 10:07
  • @oshirowanen great! glad you did it finally! Commented Nov 2, 2012 at 11:20
1
$('.txtBox').parent().next('.content').html('Whatever')
1
  • Updated question with current full script. Commented Nov 2, 2012 at 10:03
1

You have to go to parent of text box which is div and find in siblings of it,

Live Demo

var content = $('.txtBox').parent().siblings('.content');

You can also use the next of parent of text box if the given html has constant structure.

Live Demo

var content = $('.txtBox').parent().next('.content');
1
  • Updated question with current full script. Commented Nov 2, 2012 at 10:01
0
$('.content').closest('div').css('background-color', 'red');

this changes the baground clour of the closest div of class .content

1
  • Updated question with current full script. Commented Nov 2, 2012 at 10:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.