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 p
s, 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 } });
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With