Last Updated: February 25, 2016
·
8.955K
· arbaoui-mehdi

How to get content between two DIVs with jQuery

It is very simple to get content inside DIVs or inside others tags with jQuery, however, the complexity come when we try to get a particular text between two HTML tags, here is an example of problem:

I have .parent with many DIVs inside, I’m just interested by getting "Paragraph 1", "Paragraph 2" and “Paragraph 3" content.

HTML code:

<div class="parent">
    <div class="first">first</div>
    <div class="child1">child1</div>

    Paragraph 1
    <br>
    Paragraph 2
    <br/>       
    Paragraph 3

    <div class="child2">child2</div>
    <div class="child3">child3</div>

        Last Content
        <br/>
        Last Content 2
        <br/>
        Last Content 3

    <div class="last">last</div>
</div>

jQUERY solution:

var appendSt = $('.child3').after('code:'),
    content  = $('.parent').clone().children().remove().end().text(),
    reg      = content.replace(/code:([^xyz]+)/, '');
alert(reg);

Demo: http://jsfiddle.net/5USac/

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside