Manipulating jQuery object without changing the html element - javascript

I have a variable with a jQuery object, for example:
var div = $('#div_element');
How can I manipulate ONLY the div variable, without changing the #div_element itself?
I want to do some edits on the div variable and to pass it as an argument to a plugin, like this:
var el = $('#div');
el.find(':first').remove();
$().popup(el); //I wrote this plugin myself
Actually I want to display popup containing the #div element (with removed the first "child"), but don't want to change the #div element itself.

Use clone to create a copy of the element.
var el = $('#div').clone();

You can use like
$().popup($("#div :not(:first-child)"));

Related

.appendChild() an HTML element on click

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

Storing data in html dynamically (html5)

I am creating a dynamic div in html which consists of multiple checkboxes. All these checkboxes and divs are being dynamically added to the html. I need to store some data about each div in the html to be accessed by javascript later. Can anyone show me an example where data can be added and retrieved dynamically in a div? I know HTML5 allows it and there are some other hacks to do it, but I am having trouble with syntax I guess.
Try to do it using JavaScript:
SomeClass.someVariable = document.getElementById('divid');
Otherwise if you mean to access custom data that has to used as attribute in your HTML tags then use
data-XXX = 'YYY';
And access it with JS:
document.getElementById('divid').dataset.XXX;
This post explains data-* attributes.
You can create custom attributes within your divs like this:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
Notice the data- prefix. this is absolutely necessary.
Then (using jQuery) you can access the custom attribute:
$('#div1').data('text'); => "Hello. This is a custom attribute."
So using this you can do stuff like:
if($('#div1').data('text') != "FreddieBobman"){
alert("HI!");
} else {
alert("Forever Alone!");
}
The above example will alert "HI!" because $('#div1').data('text') does not contain
FreddieBobman, it is in fact "Hello. This is a custom attribute."
To create these attributes use the following:
$('#div1').attr('data-name', 'value');
Our div with id of div1 now has another attribute, data-name, and the attribute has a value of value. Of course, you can change the value of attributes as well:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
<script src="jquery.js"></script>
<script>
(function(){
$('#div1').attr('data-text', 'This is cool.');
}());
</script>
Now the div has data-text equal to "This is cool.", not "Hello. This is a custom attribute."
It is Obtain by the data attributes that you add dynamically to the elements ,And retrieve when you want !
SET Attribute :
var div = document.createElement('div');
div.setAttribute('data','my_data');
div.innerHTML = "I am a div";
document.body.appendChild(div);
GET Attribute :
div.getAttribute('data')
WORKING DEMO
you can use attributes for your html tags. Also, in html5 you can also use custom attributes
What you want is to add or retrieve data from div tags dynamically?
Using javascript function you can simply get corresponding div element using its id,
var container = document.getElementById('your_element_id');
Then you can add what you want.
var stringToAdd = "<p>something you want to add</p>";
container.innerHTML = stringToAdd;
Also you can use a different class with different features and set it as your div class.
you need to add your features inside style tag under your class name. Then,
var elementID = document.getElementById(ID);
elementID.className ="your_new_class_name";
or you can set attributes for your tag.
elementID.setAttribute('display','inline');
Using jquery with javascript,
var elementID = document.getElementById(ID);
$(elementID).replaceWith( "<p>something you want to replace</p>" );
using class name or id you can dynamically append content using,
var stringToAdd = "<p>something you want to add</p>";
$(".your_class_name").append(stringToAdd);
also you can remove whole element using,
$(elementID).remove();

How to duplicate a div in JavaScript

I was wondering how I can duplicate a DIV element a few times through JavaScript without duplicating the DIV in my html code?
Let's assume the you selected the div doing something like:
var myDiv = document.getElementById("myDivId");
The DOM API contains a cloneNode method which you can use
var divClone = myDiv.cloneNode(true); // the true is for deep cloning
Now you can add it to the document
document.body.appendChild(divClone);
Here is a short self contained code example illustrating this

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');

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