Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element is before or after another element in jQuery

Tags:

jquery

dom

Let us suppose I have this markup

<h3 id="first">First</h3> <p>Hi</p> <p>Hello</p> <h3 id="second">Second</h3> <p>Bye</p> <p>Goodbye</p> 

How can I programmatically check if an element, such as one of the ps, is after first h3 and before the second h3, with jQuery?

I am trying to do something like this:

$(p).each(function(){    if($(this).isAfter("#first") && $(this).isBefore("#second")) {      // do stuff    } }); 
like image 833
Peter Olson Avatar asked Aug 26 '11 17:08

Peter Olson


People also ask

How to get prev element in jQuery?

jQuery prev() MethodThe prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

What is prevObject jQuery?

jQuery returns prevObject if the DOM does not have the element for which jQuery is being run. You might see the element in your source at the run-time however, it is not not bound to the DOM and therefore, it shows prevObject.

How to after in jQuery?

jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.

How to insert a div after a div in jQuery?

The insertAfter() is an inbuilt method in jQuery which is used to insert some HTML content after a specified element. The HTML content will be inserted after each occurrence of the specified element. Here the “content” is the HTML content which is to be inserted after the specified target.


1 Answers

Rocket's solution works fine if sel is a real selector, if you pass a jquery object though, it won't work.

If you want a plugin that works with both selectors and jquery objects, just use my slightly modified version instead:

(function($) {     $.fn.isAfter = function(sel){         return this.prevAll().filter(sel).length !== 0;     };      $.fn.isBefore= function(sel){         return this.nextAll().filter(sel).length !== 0;     }; })(jQuery); 

Kudos to Rocket for the original solution.

like image 59
Marco Fucci Avatar answered Sep 21 '22 16:09

Marco Fucci