Search code examples
jqueryjquery-selectorselement

Find Div after specific element


I am able to grab all the HTML inside the element with the .class textimage-text. This works fine. I then need to grab the html inside the following Div, which does not have an id or a Class..

Example

<div class="textimage-text">
  <p>Some Text goes here</p>
</div>
<br>
<div>
  <p>Some additional Text goes here</p>
</div>

$.get(item.url, function (html) {

  var body = $(html).find(".textimage-text").html(); // <- this works
  var more= $(html).find(".textimage-text").next("div").html(); // <- this does not work

Solution

  • use General sibling selectors ~ (ex: ~ div find next div that is a sibling to this)

    $(html).find(".textimage-text ~ div").html();
    

    or

    $('.textimage-text ~ div').html()
    

    General sibling selectors

    The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element.

    Example:

    console.log($('body').find('.textimage-text').html());
    console.log($('body').find('.textimage-text ~ div').html());
    
    console.log($('.textimage-text').html());
    console.log($('.textimage-text ~ div').html());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="textimage-text">
      <p>Some Text goes here</p>
    </div>
    <br>
    <div>
      <p>Some additional Text goes here</p>
    </div>