Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Children of DIV after certain Number

I have this HTML

<div class="control">
     <label class="">Label Here</label>
     <input type="text">
     <div class="ui-resizable"></div>
     <div class="ui-resizable-handle"></div>
     <div class="ui-resizable-handle ui-resizable-se"></div>
     <div style="display: inline;" class="delete"><span class="ui-icon ui-icon-closethick">close</span> </div>
     <div style="display: inline;" class="properties txtbox"><span class="ui-icon ui-icon-wrench">Properties</span></div>
</div>

How can i remove the second third and fourth Divs from this HTML using jQuery....

like image 725
HardCode Avatar asked Mar 01 '12 06:03

HardCode


People also ask

How do I remove a child from a div?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

How do you remove all children from an element?

To remove all child nodes of an element, you can use the element's removeChild() method along with the lastChild property. The removeChild() method removes the given node from the specified element. It returns the removed node as a Node object, or null if the node is no longer available.

How do you delete everything inside a div?

html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Note: To remove the elements without removing data and events, use . detach() instead.


2 Answers

$('.controll>div:gt(1)').remove();

:gt selector will let you select which has index greater then 1 theese are 3. elements and more

here is example: http://jsfiddle.net/Am7Vw/1/

like image 110
draconis Avatar answered Oct 19 '22 12:10

draconis


You're looking for :nth-child: http://api.jquery.com/nth-child-selector/

It works like this:

$('.control div:nth-child(2), .control div:nth-child(3), .control div:nth-child(4)').remove();

Note that :nth-child uses one-based indexing, so the first element has index 1.

UPDATE: In response to this question the OP posted in a comment

If i dont know how many divs will occur after the input field is there any way to CUT or SLICE all the divs or any elements that occur after the second child of the Control DIV...

The answer is yes, for this you want the :gt: selector: http://api.jquery.com/gt-selector/

$('.control div:gt(1)').remove()

As opposed to :nth-child, :gt uses zero-based indexing, so the first element has index 0.

like image 32
Ben Lee Avatar answered Oct 19 '22 12:10

Ben Lee