简体   繁体   中英

Finding the closest element

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');
        }

    }

});

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!');

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');
$('.txtBox').parent().next('.content').html('Whatever')
$('.content').closest('div').css('background-color', 'red');

这改变了class .content的最接近div的背景

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM