.appendChild() an HTML element on click - javascript

I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:
It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.
$(document).ready(function() {
$('#addSubFBtn').on('click', function() {
var itm = document.getElementById("trFb");
var wrapper = document.createElement('div');
var el = wrapper.appendChild(itm);
document.getElementById("tbFb").append(el);
console.log(el);
});
});

Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp
Once you clone the node, [appendchild] should work as intended

Not sure (as said without seeing related HTML) but i see flaw in your logic:
var itm = document.getElementById("trFb");
still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place.
using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:
var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb"));
as shown here to remove element you've to use method on to parent element.
So you can add it to any other element existing.
For more specific use or element created in global JS variable (such an createElement not yet appended) you can see :document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

Related

Jquery cloned element is replacing himself

I have been getting some issue with cloning element, when I am cloning an element and add it to the DOM it work perfectly but when I am trying to clone a second one its replacing the first added clone, do you know where it could come from ?
var clone_count = 1;
var add_row = $('.modeloRowBlock-hidden').clone(true) // clone my div that is hidden
$('.add-modelo-block').on('click', function() { // binded button to add my div
var current_row = add_row.removeClass('modeloRowBlock-hidden hidden').addClass('modeloRowBlock' + ' ' + clone_count++) ;
$('.modeloRowBlock-hidden').before(current_row);
});
Thanks a lot in advance for your help :).
Jonathan.
EDIT : My bad I made it work, actually cloned that way for another reason, and re integrated it in the .on and it worked.
You clone your row only once.
If you're using before on a single element, it will move the elements.
If an element selected this way is inserted into a single location
elsewhere in the DOM, it will be moved before the target (not cloned):
Read more: http://api.jquery.com/before/

Assign java scripts to cloned HTML element

I have a html div and I clone it using Jquery. That div contains labels and text fields. ids of all of them generated and assigned dynamically. I have no problem with that.
A java script is assigned to a text field of original div. The cloned text fields does not have the javascript assigned to it.
the script I need to assign:
<script>
$(function() {
$("#datepick_onBooking,#datepick_Pay1,#datepick_Pay2,#datepick_totPay,#datepick_deedFees").datepicker();
});
</script>
the script I use to make clones:
<script>
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#addAnotherPayment').click(function() {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length+2;
cloned.insertBefore("#totPayForm");
// append count to the ids
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('input[type="text"]').attr('id', 'datepick_Pay'+ noOfDivs);
cloned.find('input[type="number"]').attr('id', 'amount_Pay'+ noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i++ + ':');
});
});
</script>
datepick_Pay1, datepick_Pay2, datepick_totPay, datepick_deedFees are static elements and they have been assigned to the script. I create text fields using cloning as datepick_Pay3,datepick_Pay4, and so on.
I cannot figure out how to dynamically assign the script to that newly created elements.How can I do that?
A Boolean indicating whether event handlers and data should be copied along with the elements.
change this line.
var cloned = $('.PayDiv0').first().clone(true);
when you clone something especially elements which having events
use parameter as
clone(true)
But this will be harmfull based on how event is attached on the actual element when copying the events to the cloned element may affect the actual.
You need to clone with events. http://api.jquery.com/clone/
var cloned = $('.PayDiv0').first().clone(true);
Then your script needs to be changed to work for dynamic elements. Here as soon as input elements gets focus, asssign the datepicker based on wild card id selector, if it doesn't already have one.
$(function() {
$('body').on('focus',"input[id^=datepick_]", function(){
if(!$(this).hasClass('.hasdatepicker'))
{
$(this).datepicker();
}
});
});

Getting the source of a click in jquery?

var currentImageBox;
$('.newImage').bind('click', function() {
currentImageBox = this;
currentImageBox.unbind('click');
});
Im trying to set currentImageBox to the div that was clicked (a number of divs on the page have the newImage class). But to no avail, where am I going wrong?
The code is correct, the this is the element clicked. But to use unbind, you need to wrap the element with jQuery since this (and therefore currentImageBox) is the DOM element and not a jQuery object.
$(currentImageBox).unbind('click');

Javascript/jQuery - How do I obtain name of the class of clicked element?

I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
​$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});​​​​
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}​
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)

jQuery $.data(): Possible misuse?

Perhaps I'm using $.data incorrectly.
Assigning the data:
var course_li = sprintf('<li class="draggable course">%s</li>', course["fields"]["name"]);
$(course_li).data('pk', course['pk']);
alert(course['pk']); // shows a correct value
alert($(course_li).data('pk')); // shows null. curious...
course_li is later appended to the DOM.
Moving the li to a different ul:
function moveToTerm(item, term) {
item.fadeOut(function() {
item.appendTo(term).fadeIn();
});
}
Trying to access the data later:
$.each($(term).children(".course"), function(index, course) {
var pk = $(course).data('pk');
// pk is undefined
courses.push(pk);
});
What am I doing wrong? I have confirmed that the course li on which I am setting the data is the same as the one on which I am looking for it. (Unless I'm messing that up by calling appendTo() on it?)
When you store the data:
$(course_li).data('pk', course['pk']);
you're creating an element but not saving it, so it's lost. Your alert test test the wrong value; it should be:
$(course_li).data('pk', course['pk']);
alert($(course_li).data('pk'));
which is null. Consider:
$(course_li);
$(course_li);
This creates two different elements with source equal to course_li, which are then promptly lost. What you need to do is create the element first, then work with that single element (i.e. don't call $(course_li) more than once). For example,
var course_li = $(sprintf('<li class="draggable course">%s</li>',
course["fields"]["name"]));
course_li.data('pk', course['pk']);
parent.append(course_li);
Note that course_li now holds an element, rather than a string.
try checking to see if the element being created by this call:
$(course_li)
is a single 'li' element, or a div. From the doco:
When the HTML is more complex than a single tag without attributes, as it is in the above example... snip ...Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in
So it's probably creating a div that you are assigning the data to, so when you select the 'li' itself, you are getting a child of the actual element that you set the data on.

Categories