JQuery DOM creation/handling issue - javascript

So, say I have selected, in JQuery, a singular DOM div.
I then proceed to create a new DIV like so:
var DIV = $("<div>Hello, world</div>");
After that, I attempt to place that DIV inside the original one like so:
$(OriginalDiv).append(DIV);
Okay, that works.
Now I want to edit DIV further.
Calls to .click, .html, .addClass, (And likely more) do not work!
Okay, instead I do:
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
DIV = $(OriginalDiv).append(DIV);
That appears to work at first; However, instead, it sets DIV to reference the same DOM object as OriginalDiv and NOT the newly appended DOM object. Naturally, this does not allow me to edit DIV.
So, then, I try two more methods:
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
$(DIV).appendTo(OriginalDiv);
and
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
DIV = $(DIV).appendTo(OriginalDiv);
Not even these work.
If I haven't done a very good job explaining, here is my exact dilemma
I am trying to create a DOM object in jquery, then append it to another DOM object using jquery. The problem is, once it gets appended, there seems to be no way for me to directly access it without using somethign like .children.
I'd like very much to be directly returned somewhere along in that process a reference to the DOM object which I am appending. As in the one that actually gets appended.
I'm not sure how to do this in JQuery. Anybody know a solution?
Thanks
--G

Yes, append won't work as it returns a reference to the element the new element was appended to. jQuery supports method chaining, so this should work easily:
$("<div>Hello, world</div>")
.click(function() {
// something
})
.appendTo('someSelector');
But even
var $ele = $("<div>Hello, world</div>").appendTo('someSelector');
will work. appendTo returns a reference to the element which was appended. If this does not work for you, you have your problem elsewhere.
Comments on your code: This is not your problem, however it is important for you to know what is going on here.
This part
var OriginalDiv = $("someSelector");
var DIV = $("<div>Hello, world</div>");
$(DIV).appendTo(OriginalDiv);
is the same as
$($("<div>Hello, world</div>")).appendTo($("someSelector"));
You see, you have a nested call to jQuery, because DIV is already a jQuery object. There is no need to pass it again to jQuery.
You can also pass a selector directly to appendTo.

you could try this;
var DIV = document.createElement('div');
then you can use;
$(div).html('Test!');
or what ever you want to use with.

You don't have to get anything back from the DOM. Once you create the element with jQuery, you already have a reference to the DOM element. Inserting it into the document does not do anything special.
// this will create the DOM element, and the jQuery
// object wrapping that newly created DOM object
// is assigned to DIV.
var DIV = $("<div>Hello, world</div>");
// Don't worry about getting a return value from this
// append() call. What we need is already available inside
// the variable DIV.
$(OriginalDiv).append(DIV);
// continue using DIV as you normally would. It is referring
// to the same DOM object that was just appended to the document.
DIV.addClass('green');

Related

Why does performing a manipulation on a variable affect the DOM in Vanilla JS?

If I want to append some HTML (a <p> tag in this case) to an element in Vanilla JS then it seems I have to do this:
const $Element = document.getElementById("ElementID");
$Element.insertAdjacentHTML("afterbegin", "<p></p>");
That works great, but what I don't understand is if I'm storing a reference to #ElementID in a $Element variable, why does manipulating the variable cause the DOM to update?
Say I wanted to do many changes to $Element like first add a <h1> tag and then a <h2> and then multiple <p> tags. I would like all of them to be done first and then ask JS to update the DOM instead of it doing it in real-time. Is that even possible in Vanilla JS?
I'm storing a reference to #ElementID in a $Element variable, why does manipulating the variable cause the DOM to update?
Because that's how references work. You can place the same reference in any number of variables, you still only have one object, and if you modify that object, the other variables "pointing" to that reference will reflect those changes, because they are all simply handles to the same object in memory.
If you want to batch changes, make a new DOM element, prepare it, and then add it to the DOM.
To accomplish what you are looking for you can always use cloneNode to clone the element you want to change, make the changes, then replace it in the dom with replaceChild on the element's parent.
var elem = document.querySelector('#target');
var clone = elem.cloneNode(true);
clone.innerHTML = "TeST";
clone.style.backgroundColor = "red";
elem.parentNode.replaceChild(clone, elem);
<div id="target"></div>

Javascript Accessing dom element directly and using a variable

Why is doing
var consoleElem = document.getElementById("debug");
consoleElem.appendChild(msgElement)
the same thing as
document.getElementById('debug').appendChild(msgElement);
It seems to me that the DOM element (debug) is its own variable, and then to copy it to another variable means I have two copies of the debug element... why should any changes I make to the new copy (var consoleElem) make changes to the original DOM element?
What is in the consoleElem isn't the DOM element itself but instead a reference to it.. so any change that's done through the reference is actually applied to the DOM element itself..
If you want to modify an element without actually changing the original element itself then you should clone it.. jQuery offers a clone functionality.
The call document.getElementById returns a reference to a DOM element. All that the line
var consoleElem = document.getElementById("debug");
does is store that reference in a variable; it doesn't create anything. You can have a dozen variables referring to the same element, and it's still just one element.
If you want to create an element, use document.createElement. If you want to copy an element, use newElement = oldElement.cloneNode().

How to access Element created by javascript document.createElement function

I'm creating a div at run-time using java-script document.createElement function.And now i need to execute another function on scrolling of dynamic created div.And also need to catch key-down event of div.
Can any one tell me how can i achieve this.
You need to insert the dynamically created div into the DOM. Without doing that, you cannot retrieve it by using document.getElementById. You can insert your dynamically created div into the element by calling a function like appendChild or insertBefore, described here http://www.w3schools.com/jsref/dom_obj_all.asp
After you find an appropriate place to insert your div into the DOM, you should be able to retrieve it from anywhere by calling document.getElementById("myDivId");. You'll also need to give that created div an id after creation, if you haven't already done so. The entire thing would look something like:
var myDiv = document.createElement("div");
myDiv.id = "myDivID"; //Give it some ID
var divsParent = document.getElementById("dynamicDivsParentElementID"); //get the element where you want to insert the div into
divsParent.appendChild(myDiv);
var retrievedDynamicDiv = document.getElementById('myDivID');
Check it out working on jsFiddle: http://jsfiddle.net/qnPUF/
You can do this by calling the scrolling function after the div element is created. Make sure the function is called after the createElement

jQuery: Detach without string selector

I'm trying to detach a DOM element to append it to another DOM element. But jQuery refuses to do anything, silently.
Thing is, I can't use a string selector, because I don't know how to select this element. I've stored it in a variable when I first appended some html code to the initial parent (through "appendTo".
this.element = $(my_html_string).appendTo(some_dom_parent);
And that works fine. The code that is not working as expected, is following:
this.transferTo = function(dom_parent)
{
$(this.element).detach()
$(this.element).appendTo(dom_parent);
}
What happens is:
The element is NOT removed from wherever it is.
The element IS appended to the new parent.
Previously bind click events are triggered on both elements.
That click event appends a popup dialog to the element. It's being appended to the element in the new parent, always, regardless which one I click.
I tried some hardcoded detach like:
$('#very_specific_id').detach()
... and it works. But thing is, I don't have IDs placed around, and sounds like a very bad way to do this.
So the problem seems to rely on the fact I'm saving a jQuery DOM Element and trying to use .detach from it, instead of using a $(".query") like everyone else.
Ideas? Workarounds? Thanks!
Try changing this:
this.transferTo = function(dom_parent)
{
$(this.element).detach()
$(this.element).appendTo(dom_parent);
}
to this:
this.transferTo = function(dom_parent)
{
var $thisElement = $(this.element);
$thisElement.detach()
$thisElement.appendTo(dom_parent);
}

How to insert created object into a div

I created an iframe using jQuery that I want to insert into an existing div element. However, when I use innerHTML to insert it, it shows up as: "[object HTMLIFrameElement]"
What could be the reason for this?
Here is the example: http://jsfiddle.net/MarkKramer/PYX5s/2/
You want to use the appendChild method rather than innerHTML. Change the last line in the JSFiddle from
iframediv.innerHTML = iframe;
to
iframediv.appendChild(iframe);
Edit to actually answer your question:
Your variable iframe is a reference to a DOM element. It's object representation is an <iframe> element while its textual representation is simply [object HTMLIFrameElement].
By using innerHTML you are attempting to insert its textual representation into the DOM. This is just how the method works. You may come across JS code where elements are added to the DOM via innerHTML, but it's always with text, e.g.
element.innerHTML = '<div>some text</div>';
In this case the browser will correctly add a <div> node as a child of element.
For your <iframe> element to be inserted into the DOM using the variable iframe, you must use the appendChild method which will add the IFrame object as a child node to iframediv.
$('#iframecontainer').append(iframe);
instead of
var iframediv = document.getElementById('iframecontainer');
iframediv.innerHTML = iframe;
should fix the problem
var new_iframe = $("<iframe></iframe>");
new_iframe.appendTo($("#div_to_insert_into"));
The idea behind (most) of the posted solutions is that you can work with your iframe and it's container as jQuery objects instead of regular dom elements. A jQuery object is a reference to a div or an iframe that has access to all of jQuery's awesome methods... like .append() and .click().
Generally speaking, jQuery's real purpose is to turn lines of code like
var iframediv = document.getElementById('iframecontainer');
...into ...
var iframediv = $("#iframecontainer");
...which you can then use to do with whatever you please, like
iframediv.appendTo("#anotherDiv");
Good luck.

Categories

Resources