Sarawut Positwinyu
Sarawut Positwinyu

Reputation: 5042

Get an element that might be a children from next element

Suppose that I want to select the nearest target element from startFromThis (only the element that come after startFromThis. the target might be a child of any unnamed or unclassed element. Is there anyway to select this.

Sorry, i would like to edit startFromThis to be an ID

<div id="startFromThis"><div>
<div>
  <span class="target"></span>
<div>

Upvotes: 0

Views: 58

Answers (3)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

You can use the .closest() function for this:

$(document).ready(function(){
    $('.startFromThis').closest('.target').html('Selected!');
});

Check out the documentation here: http://api.jquery.com/closest/

Upvotes: 1

Michael Peterson
Michael Peterson

Reputation: 1123

$('#startFromThis').closest('target element') assuming startFromThis is an id.

Upvotes: 3

Vladislav Qulin
Vladislav Qulin

Reputation: 1942

$(".startFromThis").closest().children(".target");

Upvotes: 0

Related Questions