Monthly Archive » March 2014

[jQuery] How to remove text between two divs

While working on one project, I came to weird problem:

how to get rid of text that is between two div tags and is not captured in any tags?

To be specific, here is what I mean:

<div class="first">Some content</div>
Here is our text we wanna get rid of. 
<div class="second">Some other content</div>

The problem here is, that text is not surrounded by any HTML tag. Then it would be too easy. jQuery can easy hide() or remove() content.

So how do we go about it?

Well, I googled and tried a lot of solutions (eg. trying to put ending p tag before second, and starting p tag after first div) but that didn’t seems to help. So I gave up with trying to enclose text and then remove it. Finally, I came to this code:

jQuery('.first')[0].nextSibling.nodeValue = '';

nextSibling property of DOM and does exactly what you’d expect. So then we can easy set it’s nodeValue to empty string. That’s what we wanted right?

Here is a working example.

But what if there is more of those things?

Yes, that’s exactly what I was facing. My code is more like this, in fact:

<div class="first">Some content</div>
Here is our text we wanna get rid of. 
<div class="second">Some other content</div>
<div class="first">Some content</div>
Here is more text we wanna get rid of. 
<div class="second">Some other content</div>

Here’s where the 0 from jQuery code comes in role. In fact, before we expected to have just one first div. Now we have more divs, so let’s make sure all of them got noticed.

for (i = 0; i < jQuery('.first').length; i++) {
        jQuery('.first')[i].nextSibling.nodeValue = '';
    }

Here is working example.

Is that it?

Well, yes, if the only thing you have between two divs is always only text without any more HTML tags. If you have tags there, you will need to do some extra work.

And yes, you could use remove() on nextSibling as well.