user2279668
user2279668

Reputation:

How to remove some part of HTML

My code:

<div id="main">
    <div id="div1">Keep this div</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <p>4</p>  
    <a href="">Keep this hyperlink</a>
</div>

<button id="button">Clear</button>

How can I remove everything after div with id div1 but keep the hyperlink when click the button which finally look like this:

<div id="main">
    <div id="div1">Keep this div</div>
    <a href="">Keep this hyperlink</a>
</div>

<button id="button">Clear</button> 

Upvotes: 1

Views: 1187

Answers (2)

Rishabh
Rishabh

Reputation: 2021

I am assuming you are using jQuery so a nextAll(':not(a)') should work fine.

Working Demo.

Upvotes: 2

Eli
Eli

Reputation: 14827

You can use nextAll() method along with :not and :last-child selector:

$("#button").click(function() {
    $("#div1").nextAll(':not(:last-child)').remove();
});

Working Demo

Upvotes: 2

Related Questions