Ahmad Ahmad - 1 month ago 12
jQuery Question

Get some text after the first h1 tag of the page

How can I get the text after the first

h1
tag of the page? On the page there will be some text after the h1 tag. That text can be the HTML list or simple plain text.

So I want to get some text, that can be about two sentences or we can limit by character counter after the first H1 tag of the page, if there is no text the will get the
H1
tag text.

How will I do this using jQuery?

My current HTML is:



<div class="main_content">
<h1>H1 tag text</h1>
<div class="other_text">
This is <b>some</b> text.
</div>
</div>


In this case I need
This is some text
.

Or it can be like the following as well:



<div class="main_content">
<h1>H1 tag text</h1>
<ul>
<li>first element</li>
<li>second element</li>
</ul>
</div>


In this case I need the first two li's contents.

Answer

I guess what you can do in this case is to make use of .next() and .text(). So, let's try with both of your cases.

$(function () {
  console.log($("h1").next().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_content">
  <h1>H1 tag text</h1>
  <div class="other_text">
    This is <b>some</b> text.
  </div>
</div>

And for the next case, let's try with the same code:

$(function () {
  console.log($("h1").next().text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main_content">
  <h1>H1 tag text</h1>
  <ul>
    <li>first element</li>
    <li>second element</li>
  </ul>
</div>

Hope this helps and works! :)