Azeem Haider
Azeem Haider

Reputation: 1513

Remove next element in jquery

I want to remove next element using jquery here is my code please check it.

  <span id="t1">Test 1</span><br/>
  <span id="t2">Test 2</span><br/> // I want to remove this <br/>
  <span id="t3">Test 3</span><br/>

Here is a jquery code but this is not working.

   $('#t2').next().remove();

I want to remove <br/> which is after the t2.

Upvotes: 2

Views: 8829

Answers (5)

JugalK
JugalK

Reputation: 146

Maybe your code is working. Because there is nothing wrong in the code. It should work.

Maybe your CSS is the actual problem.

If your css is set to display <span> in the next line (display block or anything else) it will not show code's effect. Though it's just an assumption but it's better to check that out.

And as @Dev and @Sidharth said it's better to keep a selector in the next().

Upvotes: 0

Ehsan
Ehsan

Reputation: 12959

Try this :

$(document).ready(function(){

    $("button").on("click",function(){

        $("#t2").next().remove("br");

    })
})

Final code :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    
    
    <span id="t1">Test 1</span><br/>
    <span id="t2">Test 2</span> <!--I want to remove this--><br>
    <span id="t3">Test 3</span>
    <br><br>
    <button>Remove</button>
    
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    
    <script>
        
    $(document).ready(function(){

        $("button").on("click",function(){

            $("#t2").next().remove("br");

        })
    })
    </script>
     
    </body>
</html>

Upvotes: 3

scaffolding
scaffolding

Reputation: 163

You need to bind your jQuery code to some sort of event, like https://jsfiddle.net/ps2aoey7/

Also, in this case you don't need the next() function.

HTML

  <span id="t1">Test 1</span><br/>
  <span id="t2">Test 2<br/> // I want to remove this <br/></span>
  <span id="t3">Test 3</span><br/>

jQuery option 1 (click event)

$( "#t2" ).click(function() {
  $('#t2').remove();
});

jQuery option 2 (on page load)

$( document ).ready(function() {
  $('#t2').remove();
});

Upvotes: 0

Dev. Joel
Dev. Joel

Reputation: 1137

using nextAll method allows us to search through the successors of these elements in the DOM tree

if one ahead br element

$('#t2').next('br').remove();

if not

$('#t2').nextAll('br').remove();

Upvotes: 2

Sidharth Gusain
Sidharth Gusain

Reputation: 1501

$("#t2").next("br").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="t1">Test 1</span><br/>
<span id="t2">Test 2</span><br/> 
<span id="t3">Test 3</span><br/>

This might help you.

Your jquery code is working fine but the main problem was your comment in the html code

// I want to remove this <br/>

It should be

<!-- I want to remove this <br/> -->

Upvotes: 2

Related Questions