jquery: how to remove the previous element? - javascript

how do i remove a previous element to the triggering one with jquery?
i have tried:
$(this).prev().remove();
$(this).next().remove();
but nothing works!

Be sure jQuery is properly referenced, and all of your syntax is correct:
$("li").click(function(){
$(this).prev().remove();
});
Works with:
<ul>
<li><p>Don't delete me!</p></li>
<li><p>Click me to delete him!</p></li>
<li><p>Click me twice, to take 'em both out!</p></li>
<br/> <!-- line break added after OP's comments -->
<li><p>Click me to remove the line-break!</p></li>
</ul>

Often when seemingly correct jQuery syntax doesn't work (especially with traversing) it is often because you are operating on the wrong element. Take a look at this HTML:
<div>
Please remove me
</div>
<div>
<span>Click to remove</span>
</div>
Now, if we wired this up with a click event on the span it is important to first call parent() to get the containing div, and then get the previous element:
$("span").click(function(){
$(this).parent().prev().remove();
});
A simple call to $(this).prev().remove() would fail because the span is the only child of the div.

The exact code you posted works for me.
Note that this is always set to an element in e.g. a jQuery click handler, but not in other JavaScript functions (unless you arrange for it to happen that way).

We'll be better able to answer your question if you provide a little more context. Note that this won't necessarily point to the current element unless you are within the context of a handler. What are you trying to achieve here?

Related

html append to already appended div does not work with appendTo

i have an appended div, what i want is to append a div with the appended one.
please see the codepen of my code which is well explained with comments.
here is the structure i want:
DIV 1 --> DIV 2(append with div1) --> DIV 3(Append to already appended Div 2)
i tried to use appendTo(); and also $('#clsDashRegion_levelThree').find('#clsDashRegion_siteAlmCriticite').append(infoRegionSiteCriDetails); but it does not work. if you can help me please make it work, thank you !
To be honest the code is quite bad. There are much better ways to accomplish what you want, but nevertheless here is your fiddle slightly modified. Please tell me if the behavior is what you want:
https://codepen.io/anon/pen/OjNXWv
One important thing is that the id in the second div that you want to be clickable does not receive direct events because it was generated dynamically. So you have to use event delegation like so:
$(document).on('click','#clsDashRegion_siteAlmCriticite',function() { ...
After the
$('#clsDashRegion_levelTwo').html(infoRegionCriticite);
});
Shouldn't you then call
levelThreeCriticiteDetailsBloc()
Otherwise when you click '#clsDashRegion_siteAlmCriticite' nothing will happen.

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

Does jQuery remove function really remove Dom elements?

I am really wondering if jQuery remove function really remove elements from DOM.
First, I looked here but the answers are not convincing.
I encountered this problem when I noticed I am still able to manipulate elements on which I have called remove function.
My code:
<div id="container">
<div id="div">
This is a div
</div>
</div>
var div = $('#div');
$('#div').remove();
$('#container').append(div);
Note: My question is not how to solve this? but I want to understand what's going on here!
Actually, this code doesn't remove the #div from the dom, but if I have any data set to the #div, it will be lost. I am pretty confused now about the behaviour of remove function. Can anyone explain this please?
DEMO
I am convinced that div variable is not just a clone of the dom element, is a reference to it, because when I manipulate the div variable, (like div.html('something')) the div within the DOM get updated.
Or am I wrong?
remove() does indeed remove the element from the DOM.
However in your example, the element has been cached in memory because you assigned it to the div variable. Therefore you can still use it, and append it again, and it will still contain all the events the original did.
If what you say is right, why I loose the data bound to the div so?
If you check the source for remove() you'll see that it calls the internal cleanData function which removes the events and clears the data cache for the element. This is why you lose the information.
If you want to remove the element from the DOM, but keep the elements, use detach() instead.
Here's a fiddle to show the difference: http://jsfiddle.net/2VbmX/
had to delete the assigned variable:
delete div;

jquery selector to get all anchor elements within a given div, no matter how deeply they are nested?

suppose some markup such as:
<div id="header">
<div id="nest-one>
one
<div id="nest-two">
two
three
</div>
</div>
</div>
and I want to tie a single click handler to all of the a tags.
I tried the following, but didn;t seem to work. I know I'm missing something stupid easy, just not sure what it is.
$('#header a').click(function(){alert('on click')});
On this line:
<div id="nest-one>
You've missed the closing double-quote on the id.
Aside from that, make sure any JavaScript referencing HTML elements is in the document ready function and/or after those elements in the source.
Demo
EDIT
per BoltClock's point:
This works actually
$('#header a').click(function(){alert('on click')});
Use $.live or $.delgate, this will also bind to any future elements added dynamically to the DOM.
example:
$("#header").delegate("a", "click", function() {
console.log("%o clicked", this ); // log object in firebug
});

How to make function work after append

For example i'm using append, and for example i'm appendig button in to a div, and i have function $('button_id').click(... etc to work affter i append the div, how can i do that.I mean i get no errors, but the function is not starting, it's because i append and then i want to use the function but how to do that, i tryed with delegate, but same thing.I tryed with function in the button tag , onmouseover and then the function thing, but nothing it gives me function not found.What is the solution ?
I have two events, one event is click event that appends button, the other event is click event that does something if the button that was appended is clicked, but that second event is not working ?
Try using :
$(elem).live(...)
It will bind event for now and in the future.
Firstly, it always helps if you show us the exact source code. $('button_id') is the incorrect selector to start with, try something more along the lines of $('#button_id') as your selector. Also, are you appending dynamic content? Anyways, I've always used the delegate() function quite successfully, but have you tried using the live() function? Also, one more thing to make sure of is that you have the newest version of jQuery as your source.
As was stated as well, you can not have duplicate ids, if you want to have a pointer, use class, instead of id="some_id" use class="appended". To select those using jQuery, use the selector like this $('.appended').
Try something like this it will work as per your expectations.
$("#button_id").click(function(){
//On click code goes here
}).appendTo($("#div_id"));
It's difficult to determine the problem you're having without seeing your code, but delegate (or live) should be perfect for what you're trying to do:
$("body").delegate("#b", "click", function() {
alert("ok");
});
$("#example").append('<input type="button" id="b" value="Click" />');
The click handler above will fire when an element with id="b" is clicked, whether or not that element happens to be in the DOM right now or not.
However, as others have noted, it's important to remember that IDs need to be unique within a document, so by the sounds of it you may be better of using classes instead.
You can see an example of the above code running here.

Categories

Resources