obj.parentNode.replaceChild(elem,obj)
Now I want to have a handle to that inserted node.
The "elem" handle is still valid even if it has been inserted into the DOM.
So you can simply use elem to access the element that has replaced the old element.
Use the reference you already have: elem. That's the element you just added. The replaceChild call doesn't create any new nodes.
If you're doing something like this:
obj.parentNode.replaceChild(document.createElement('div'),obj)
...you'll not end up with any reference to the new element. You'll need to first retain it manually:
var elem = document.createElement('div'); // Create & reference the new element
obj.parentNode.replaceChild(elem,obj); // Perform the replace
MDC Docs
Related
let myElement = document.createElement("div")
I can access the element by:
myElement.anyMethod
But I can not access by:
document.body.myElement.anyMethod
So why can we access body by:
document.body.anyMethod
But we can not access the element by:
document.body.myElement.anyMethod
CreateElement
Let's make this simple. In DOM all the elements are treated as objects.
The document is also an object with attributes like body and methods like clear, location, and so on. So when you are creating an element with
let x=document.createElement('div')
console.log(typeof(x))
//returns object
The CreateElement returns an object and it does not create an attribute or anything for it. So the element is not connected to the document object.
Methods
x.click()
X is an object of HTMLElement and has methods like click and attributes like id and so on. But when you are doing like this
document.body.x.click()
The document has an attribute named body but the body object has no attributes like x
document.body.x //returns undefined
So finally the createElement method returns an object but it doesn't add the element as its attribute so when you are calling like this you get an undefined error.
You're missing a step in your code if you're expecting to reference it from the DOM (via document.body... or document.getElement...). You need to append the element to a particular place where you want it. This reference page shows a simple example, but I'll share an example related to your code here:
let myElement = document.createElement("div");
myElement.innerHTML = "It works!";
// you can replace the following with `document.body.append(myElement)`
document.getElementById("body").append(myElement);
<div id="body"></div>
I'm just starting with JQuery and am working through a tutorial vid. At one point the presenters go for javascript instead of a JQuery selector. Just wondering why the javascript getElementById below works fine when passing an object to a function, but the second one doesn't?
Thanks!
// works
addTask(document.getElementById('taskText'), evt);
// doesn't
addTask($('#taskText'), evt);
getElementById() returns a DOM element reference.
jQuery's selector returns a jQuery object. You can get the element reference from the jQuery object using
$('#taskText').get(0);
See http://api.jquery.com/get/
To add to the other answer, regarding the result, if you want to use jQuery (which is easier to read), you can get the dom node directly like so:
addTask($('#taskText')[0], evt);
$('#taskText') returns a jQuery object reference.
document.getElementById('taskText') returns a DOM element reference.
If your addTask() function doesn't know how to convert them to what it needs, then that would be the issue since one of them will need a conversion.
If you want to get the first DOM element reference from the jQuery object, you can do so with this:
$('#taskText').get(0)
So these two should be identical:
$('#taskText').get(0)
document.getElementById('taskText')
Both are not exactly same
document.getElementById('taskText'); //returns a HTML DOM Object
var contents = $('#taskText'); //returns a jQuery Object
var contents = $('#taskText')[0]; //returns a HTML DOM Object
so you have to change it to get HTML Dom Object
addTask($('#taskText')[0], evt);
As #Phil and #jfriend00 have pointed out, document.getElementById('taskText') is a DOM element, and $('#taskText') is a jQuery object. The latter is an object of all DOM elements that match the selector.
Think of it as a zero based array, you could pass in the DOM element by doing this:
addTask($('#taskText')[0], evt);
In JavaScript if I append a child which has an ID to another place then it's removed from original location where they currently are.
In javascript I have an event where I can get selector by using this inside the function
$('.').event(function(){
this
});
This is passed to another function and they work fine. Now I want to pass the clone instead of the object; and remember that this does not have ID.
The old code works by passing this to function as DoSomething(this)
if I make a clone using jQuery clone then I have the jQuery object. So how do I get a reference to this instead of the jQuery object when working with the clone?
var clone = $(this).clone() // this is jQuery object.
//how do I get this out of clone?
if I append a child which has an ID to another place then it's removed from original location where they currently are.
Yes, but the same is true of a child node that doesn't have an id attribute as well. An id is only an easy way for you to get a reference to the Element node object; it makes no difference to DOM insertion of cloning behaviour.
In javascript I have an event where I can get selector by using this inside the function
No, this in an event handler gives you the DOM Element node object, not a selector string. A Node can be turned into a jQuery wrapper around it using $(node) and a selector can be turned into a jQuery wrapper on the list of matching nodes using $(selector) but other than this overloading in the jQuery API they're completely different animals.
To pull a Node back out of a jQuery wrapper you can use the get() method or simple array-like access:
var clonedNode= $(this).clone()[0];
var clonedNode= $(this).clone().get(0);
to taste. (get() has some extra features which you don't need here.)
To get the selector used to create a jQuery wrapper you can use the selector property, but this won't return anything if the wrapper was created from a node object ($(this)) rather than a selector.
$(this).clone().get(0). This will get the first matching DOMElement from the jQUery object.
To get the DOMElement object from a jQuery object use get(0):
var clone = $(this).clone(); // this is jQuery object.
var el = clone.get(0); // this is DOMElement object
I'm writing a script to replace some images with divs in jQuery. I'm currently using the replaceWith() method, which works fine, but returns the original (removed) element instead of the new element.
The .replaceWith() method, like most
jQuery methods, returns the jQuery
object so that other methods can be
chained onto it. However, it must be
noted that the original jQuery object
is returned. This object refers to the
element that has been removed from the
DOM, not the new element that has
replaced it.
How can I get a reference to the new DOM element I just created?
$.fn.replaceWithPush = function(a) {
var $a = $(a);
this.replaceWith($a);
return $a;
};
See a working demo
I believe replaceAll() returns the new content. It has the target and source reversed from replaceWith().
var newobj = $( "<p>New paragraph" ).replaceAll( "#replaceme" );
Precede your call to replaceWith() with a jQuery call to find the parent node and then use the parent to find the new node that was inserted with the replaceWith() function.
Here's an example inside the success handler of a $.ajax() function that replaces a form:
success: function(data,textStatus,jqXHR){
var $li=$form.parents('li');
$form.replaceWith(data);
var $form=$li.find('form');
//...
},
In this example, there was a unique form for each li. You may need to tailor your approach depending on how you construct your DOM.
Is there a way to remove a dom element from the document, but save it as a variable? I'm guessing I have to save the clone as a var, and then remove the original?
Also, would such a technique store styles etc?
Yes, that's what you do.
var savedElement = document.getElementById('element_that_you_want_to_save');
savedElement.parentNode.removeChild(savedElement);
// savedElement will still contain the reference to the object,
// so for example, you can do:
savedElement.style.height = '100px';
document.getElementById('container').appendChild(savedElement);
// etc.