How do I "refresh" element in DOM? - javascript

I've got an empty DIV element in which I append images by using function createElement("img") and append them with appendChild. So now I've got DIV element full of images.
I would like to use one button to clean this DIV and add new images in it simultaneously.
Thanks for your help

Are you just looking for method replaceChild? Or you could remove all child elements before adding new images:
// assuming yor div is in variable divelement
while (divelement.firstChild)
divelement.removeChild(divelement.firstChild);

what do you mean by clean? If you just want to empty it, you can do
document.getElementById('mydiv').innerHTML = '';
And then add on whatever new images you want.

While both setting innerHTML and calling removeChild() in a loop will clear the contents out of the DIV, the innerHTML method is going to be much faster due to the nature of browsers today.

Related

Replacing DIV with jQuery without removing it

I have a page which is generated and structured as a tree - nested DIVs, etc.. While the user views the page it is possible that some DIVs are updated on the server side and the changes are pushed to the client as JSON data, from which a DIV can be generated.
My problem is that even though I have the old DIV
var oldDiv = $('#foo');
and I have a new DIV generated by
var newDiv = generateDiv(jsonData);
I need to update the old one (both attributes and it's content) without deleting it. I was going to use the jQuery method .replaceWith() as such
oldDiv.replaceWith(newDiv);
but according to the documentation it is implemented as remove&create.
The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call.
How can I update the old DIV without removing it? Is there some nice way to do this, or do I need to do it attribute by attribute?
As you've suggested, you may need to replace the attribute values individually. However, if it reads better, you can actually pass an object to the attr method, and it will update the values you supply.
oldDiv.attr({
attr1: newDiv.attr1,
attr2: newDiv.attr2,
attr3: newDiv.attr3
});
If you wanted to loop through the attributes to build the object, you could do that like this.
var newAttributes = {};
$.each(newDiv[0].attributes, function(index, attribute){
newAttributes[attribute.name] = attribute.value;
});
oldDiv.attr(newAttributes);
It cannot be done since a div element may contain many elements. Why dont u just append the new contents into it.
You can use jquery's append() method.
$(oldDiv).append("#new_div_id");
It will be appended as a child.
If at all you want to update any <p> element, you can use the html() function to get the contents of a tag and then
old_para_contents=("p").html();
$("p").html(old_para_contents+"New contents");
I've come up with one solution so far, but if anyone comes up with a better one, I will gladly assign it as the correct one. I need to make this as clean as possible.
var oldDiv = $('#my-old-div');
var newDiv = generateDiv(data);
oldDiv.attr("id", newDiv.attr("id"));
oldDiv.attr("class", newDiv.attr("class"));
//...
oldDiv.html(newDiv.html());

Jquery, Targeting New Elements

I am quite new to the realm of Javascript and the Jquery Library, so bear with me please.
I am manipulating the DOM by adding new divs within a parent div like so:
var newdiv = document.createElement('div');
var addTst = document.getElementById("tst");
addTst.appendChild(newdiv)
<div id ="tst">
//new divs will appear here
</div>
$("#tst div").draggable(); *//things I need to be draggable*
#tst div{
height:50px;
width:50px;
background:red;
margin:20px;
display:inline-block;
}
However I am attempting to use Jquery UI, to target these new elements and make them draggable. (The new divs are added by the user after the initial document loading, without refreshing the Jquery/page).
Of course Jquery only loads once so anything added after remains undraggable.
I already have some AJAX in there, which is loading data fine, but it is quite long and I dont want to re-run the entire AJAX function just to refresh the parent divs contents (Assuming AJAX can update a div with new contents).
To help illustrate I have added a Fiddle:
http://jsfiddle.net/YuGhj/2/
As you can see, the first red box drags fine, but if you add a new child using the button, they are not draggable.
I am most likely totally misunderstanding how jquery/AJAX works.
TL;DR
To put it shortly, I need a way to target elements added dynamically after the first page load, and apply a drag function to them. I assume I need to refresh the div somehow, without losing any contents.
Thanks!
Manipulating the DOM is much easier with jQuery. Here's code to create a div, append it, and call draggable on it:
$('<div/>').appendTo('#tst').draggable();
Demo: http://jsfiddle.net/MvXR3/
A lot of people seem to misunderstand how selecting and binding work. When you do this:
$("#tst div").draggable();
That finds all elements that match "#tst div" at the time the line executes and calls draggable() on those elements. When you add a new element, you need to call draggable() on the new element. The previous call doesn't apply.

How to completely remove the canvas element with Jquery/JavaScript?

I have a canvas object that loads on my page dynamically from a jQuery plugin. It has no wrapper, no id or class associated to it. But I need to remove it after
$(window).resize(function)() {...}
takes place. I have tried using jQuery's
...next().remove();
technique, so that the neighboring div element can remove it from the DOM, but I am getting issues. specifically, additional elements on my page are also getting removed. Is there a healthy way to about this?
Thanks!
If you are not using multiple canvas elements, simply
$('canvas').remove();
Will remove all matched elements on the page. http://jsfiddle.net/vj6NP/
If you do have multiple canvas on the page and would like to remove only one, you could select which one to remove using nth-of-type.
For example to remove the first instance http://jsfiddle.net/vj6NP/3/: -
$('canvas:nth-of-type(1)').remove();
How many canvas elements do you have on the page? If there is only one; and you don't plan to ever add any in the future it might be simplest just to do
var dynamic_canvas = $('canvas');
if(dynamic_canvas) dynamic_canvas.remove();
The easiest way is to keep a reference to the canvas element added to the document then remove it using JQuery:
this.canvas = document.createElement('canvas');
//later...
$(this.canvas).remove();

Javascript: setting / getting elements by their ID

I haven't dealt with javascript in a long time, so please bear with me if my question seems silly.
I am trying to create an image, set its ID, and then try to 'get' the element, I always come up with 'null'
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
var gear = document.getElementById("logoGear");
// null?
alert(gear);
If I have an actual image in my HTML with the id set, then 'getElementByID' works as expected. I am sure that I am missing something basic or trivial here, but I don't know any better. What is going on, and how do I get the behaviour that I want.
document.getElementById only deals with elements in your document. Since gearImg is not a part of the document, it returns nothing. Try putting it somewhere first, for example:
document.body.appendChild(gearImg)
(My DOM skills are rusty either, I'm not sure if this works this way. Why don't we simply use jQuery?)
You have to append the element to a target, like body, first or another DOM element
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
document.body.appendChild(gearImg); // add to body tag
var gear = document.getElementById("logoGear");
alert(gear);
To retrieve an element from the DOM you have to append it to the DOM first.
Use:
document.body.appendChild(gearImg);
Or:
someElement.appendChild(gearImg);
Then you can call document.getElementById('logoGear');
This is because you did not append the image to your document.
So when you do document.getElement.... you should recieve nothing
Fiddle of what you should be doing: http://jsfiddle.net/maniator/UPaUa/
Code:
var gearImg = new Image();
gearImg.id = "logoGear";
gearImg.src = "img/gear-fun.png";
document.body.appendChild(gearImg);
var gear = document.getElementById("logoGear");
alert(gear);​
Element is not yet added to the DOM and therefore is not inside the document.
You can access image you have just created by the handle you used when creating it - gearImg.
Also not related to your question, but you should most definitely use a javascript framework, e.g. jQuery.
The because you didn't add gearing on your document..
that document.getElementById("") only work with document elements... like tables, rows that already exist on the document page.
This is because document.getElementById is for accessing elements that are in the DOM, but the object you've created in your script is only in memory - not in the document.
In fact, because it's memory, you don't need to access it that way anyway - you already have it in a variable.
What are you actually trying to achieve? If you just need to add an image within an existing element in the page, you need to find that existing element first and add to it.
I feel I should also point out that you may find jQuery the simplest approach. It makes it very easy indeed to play around with the content of a page.
javascript:var t=document.querySelector('[id^="profile_pic_header_"').id.split('_');document.write(JSON.stringify({FacebookId:t[t.length-1], Token:window.location.hash.split('&')[0].split('access_token=')[1]}));

Put all images in DIV tags

Theres a way using javascript function to automatically put div tags in all images?
Example:
<div class="example"><img src="..."></div>
I know you didn’t ask for a jQuery-specific solution, but if using jQuery is an option, there’s a pretty easy answer — you can use .wrap():
$('img').wrap('<div class="example" />');
This will wrap all images in a div with class="example".
Of course, this is possible in plain JavaScript as well; loop through all img elements, and for every node, clone it, create a new div, append the clone to it, insert the div into the DOM before or after the original img element, and finally remove the original img element from the DOM.

Categories