Appending already present element to DOM with Javascript/jQuery - javascript

I have an element in my DOM with two children, a div block and a button. When I click the button, I want to add a new copy of the same div block to the parentNode. Is this possible? What I have in the button onclick call now is:
document.getElementById("myele").appendChild(document.getElementById("myele").children[0])
But this just moves that child in the children array under the button, and if I click again moves the button back under the div block (this because now children[0] is the button itself). I've also tried to assign the child Node to a variable and append that instead, but the result is the same.
Is there a way to do what I'm trying to do without having to call a JS function that recreates the whole div block and then appends it?
EDIT: Having never used jQuery, I also tried to do this, but it doesn't seem to work:
<script>
function addOne(){
console.log('click')
$('.valori:first-child').clone(true).appendTo($('.valori'))
}
</script>
and the onclick call became:
javascript: addOne()
The console logs 'click', but no changes in the page.

Assuming I've understood you right, cloneNode may be what you are looking for.
You could clone your element and then append the clone to your parent node.
https://developer.mozilla.org/en/docs/Web/API/Node/cloneNode

Related

Re-printing a div without having to refresh the page (incursion?)

I've been stuck with this for a while and have tried a few different things to no avail.
I have a function that prints elements to a page. Within that function, I have an addEventListener that upon click will change the order of those elements. When I refresh the page, it works, and the order is changed. However, I'd actually like the order to be changed upon click.
My original thought it calling the function within itself which I've tried but that doesn't seem to work. Any thoughts here?
printElements()
{
//prints elements to the page
addEventListener('click', function(event)
{
//changes order of elements
div.innerHTML = ''
printElements()
}
}
First get the info of the elements in array or object
Second remove all the elements
Third create the elements and set the info that you stored to them
Last append the the elements in order
that you want

jQuery get parent with specific class

I am listening to clicks on an element with a specific class. When I click inside this element I want to get this element, not the children I clicked on. How do I avoid getting children back when I call
event.target
Here is fiddle I created to demonstrate the problem
https://jsfiddle.net/yxvfgkcs/
Since I get children back they get CSS applied to them instead of the parent.
How do I figure out I have clicked on a child of element and get the element with class selectable back?
Since you're already using jQuery you can use .closest():
var clickedField = $(e.target).closest(".selectable");
See updated JSFiddle

Jquery double click event after appending element to another element

I'm using agile toolkit, a framework that generates javascript code from PHP. I have a div element (I'll call it "top-element") that contains some other div elements, some buttons.
I want to move the "top-element" to another element, to change it's parent.
I tried something like:
$('#top-element').appendTo($('#new-parent'));
But the problem is that the "top-element" have some childrens that have click events, some buttons. After I append the "top-element" to a new element (after changing it's parent), the click events are triggered twice.
I tried to clone the element and append the cloned element to the new parent:
var cloned_top_element = $('#top-element').clone(true);
cloned_top_element.appendTo($('#new-parent'));
I got the same problem, the click event on "top-element" childrens was called twice.
The way to prevent double click is to use:
unbind('click') or off('click')
I tried something like:
$('#new-parent').find('.children-class').unbind('dblclick').unbind('click');
But still no results.
The binding for child buttons is like this:
$('.children-class').bind('click',function(ev){ ev.preventDefault();ev.stopPropagation(); other stuff });
The bind function appears only once. There aren't duplicates in the js code.
Any ideas? Anticipated thanks.
Remove the true in the clone function .clone(); this will not copy the event handlers

Child's event is not fired when parent's HTML is changed

Here's an example http://jsbin.com/ukoqud/3/edit
If you click on a red box, you'll get an alert.
If you click on a link, everything in a blue box will be replaced with just a red box. Link will disappear and if you click on a red box then, you'll get no alert.
Why this happens?
Is it related to innerHTML?
Does it work the same way in all browsers?
Here's one more example http://jsbin.com/ukoqud/1/edit In this one you'll get an alert after clicking on a link. Things happen in a quite similar way, but result is different.
I would like to understand the reason, there's no need to fix my code.
When you call $(".red"), it returns a collection of DOM elements that exist at that moment. So $(".red").click(function...) just binds a handler to the click event on those elements. If you later create new elements with the same class, they weren't in this collection, so they don't have the handler bound to them. jQuery doesn't watch the DOM for changes and update the handlers dynamically -- the bindings are just on the elements you matched at the time you called click().
You either need to bind the handler again after adding the new HTML, or use delegation with .on():
$(".blue").on("click", ".red", function(){
alert('click on a red box detected');
});
This works by binding a handler to $(".blue"), which doesn't change dynamically. The handler checks whether the element you clicked on matches the ".red" selector, so it's able to handle dynamically-added elements without requiring rebinding.
I think the reason why it works in your second example is because the red block isn't inside the blue box to start. When you move it inside, jQuery reuses the same DOM elements, so the bindings go along with it. In the first example, the red box starts out inside the blue box. When you do $('.red').parent().html(...), the first thing it does is empty $('.red').parent() (the blue box), so the original red element is removed from the DOM, and its bindings are lost.
We need to understand how setting html of an element works. Then you will figure out your answer yourself.
Take a look at this bin Updated Bin
When we set HTML of an element, it first removes all the elements inside it.
Those elements are not removed from memory depending upon whether they are garbage collected or not.
If any of the child is having a reference, then that particular child won't be garbage collected.
In your case, we are having a reference to red element so it is still present in memory but not a part of document.
When we say blue.html(red) in my example, red element becomes a part of document again but this time there won't be any handlers on it So your click does not work.
While in your example2,
red element is always a part of document hence no handlers were lost when red element is moved inside blue element.
I hope this will help.
because when u click the link, you delete everything on screen and create everything from a scratch and event binding goes away. so you should use this
$(".blue").on("click", ".red", function(){
alert('');
});
this way, binding is done differently. it doesnt bind it statically

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

Categories