How to get updated DOM element javascript - javascript

I am trying the fetch dynamic DOM elements from javascript and as per the current development, I can successfully fetch the updated DOM HTMLCollection array object. But when I try to print the innerHTML it gives previous DOM value. Below the console output which I am facing right now:
Console output for HTMLcollection: Highlighted part, that I want to fetch:
But when I try to get innerHTML for that element, I am getting the previous innerHTML instead I want to print current DOM innerHTML. Below is the screenshot of the output:
as we can see both screenshots of the same DOM element, gives different output. and this is javascript code I am trying fetch innerHTML:
var $wrap = document.getElementsByClassName('single_variation_wrap')[0];
var $deposit_amount = document.getElementById('deposit-amount');
var $display_amount = document.getElementsByClassName('woocommerce-variation single_variation');
$display_amount = $display_amount[0];
var $final_display_amount = document.getElementsByClassName('woocommerce-variation-price');
console.log($deposit_amount, $final_display_amount);
for(var i=0; i<$final_display_amount[0].childNodes.length;i++){
console.log($final_display_amount[0].childNodes[i].innerHTML);
}
Please suggest, where am I doing things wrong?

Related

Saving DOM Element into localStorage

I am trying to save a variable that contains HTML Element, into localStorage, this way I can call that variable again (from localStorage) anytime I want.
I am executing the javascript in the background & content script of chrome extension
So I create the variable and load it with the HTML Element that I want to save:
var btnelm = document.getElementById("ELM_ID");
I then attempt to save that variable into localStorage (hoping to be able to use that variable later)
localStorage["btnelm"] = btnelm;
But when I called the localStorage which I need it to contain the html element in my variable
localStorage["btnelm"]
I get this string text (and not the actual html element that was in my btnelm variable:
[object HTMLInputElement]
Which of course means, when I treat localStorage["btnelm"] as a variable containing my html element, it does not work:
localStorage["btnelm"].innerHTML returns undefined
I understand that localStorage stores only string values, so what are my options to be able to store my
btnelm and when called, be able to treat it as when I first created (i.e. accessing it with .childern for example)
Thanks in advance
You can't save the DOM element itself... But you can save its outerHTML.
<div id="ELM_ID">My Div</div>
var btnelm = document.getElementById("ELM_ID").outerHTML; // <== here
localStorage["btnelm"] = btnelm;
console.log(localStorage["btnelm"]);
The outputs is :
"<div id='ELM_ID'>My Div</div>"
EDIT
To use the outerHTML once retreived... And look for its properties as is was a real DOM element, simply use the .createElement() method to "recreate" it...
let tempElement = document.createElement("div")
tempElement.innerHTML = localStorage["btnelm"]
console.log(tempElement.children[0].innerText) // Will output "My Div"

Store data on element before appending

I want to store JSON on an html element using jquery data(). However my elements are actually an html string and are not yet in the DOM like so.
$(".test").each(function() {
el += "<span>"+ 25 +"</span>";
});
$("body").append(el);
I have tried this (within each function)
el += $("<span>"+ 25 +"</span>").data("test", {"name":"john"});
But when I append el, I get [object][object] appended instead
How can I associate the data with the element and be able to retrieve it after its appended?
FIDDLE: https://jsfiddle.net/6mhgwtk1/1/
You did it right, but it's an object. When you print or alert an object it will always appear as [Object]. Instead of printing the object print it's properties instead, like this: el.data("test").name.
see: https://jsfiddle.net/6mhgwtk1/
Based on your example code, I've updated your fiddle with working code. See the comments for the explanation.. https://jsfiddle.net/6mhgwtk1/3/
var el;
$("div").each(function() {
// el is not a string here, (it's a jQuery object) so you can't concatentate it using +=
// instead you will have to append each one to the body separately
el = $("<span>"+ 25 +"</span>").data("test", {"name":"john"});
$("body").append(el);
});
$("body").find("span").each(function(){
var data = $(this).data("test");
console.log(data);
});
For retrieving, Try getting attributes of el (since it is an object).

How do I copy an HTML document and edit the copy based upon the selection, without altering the original document?

I have an HTML document, and I would like to remove some of the tags from it dynamically using Javascript, based on whether the tags are within the current selection or not. However, I do not want to update the actual document on the page, I want to make a copy of the whole page's HTML and edit that copy. The problem is that the Range object I get from selection.getRangeAt(0) still points to the original document, as far as I can see.
I've managed to get editing the original document in place with this code:
var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
var allWithinRangeOfParent = node.getElementsByTagName("*");
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
// The second parameter says to include the element
// even if it's not fully selected
if (selection.containsNode(el, true) ) {
el.remove();
}
}
But what I want to do is to somehow perform the same operation with removing elements, but remove them from a copy of the original HTML. I've made the copy like this: var fullDocument = $('html').clone(); How could I accomplish this?
Either dynamically add a class or data attribute to all your elements on load before you clone so that you have a point of reference then grab the class or data attribute on the common ancestor and remove it from the clone. I can give an example if you like? Along these lines - http://jsfiddle.net/9s9hpc2v/ isn't properly working exactly right but you get the gist.
$('*').each(function(i){
$(this).attr('data-uniqueId', i);
});
var theclone = $('#foo').clone();
function laa(){
var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
if(node.getElementsByTagName){
var allWithinRangeOfParent = $(node).find('*');
console.log(allWithinRangeOfParent, $(allWithinRangeOfParent).attr('data-uniqueId'));
$.each(allWithinRangeOfParent, function(){
theclone.find('[data-uniqueId="'+$(this).attr('data-uniqueId')+'"]').remove();
});
console.log(theclone.html());
}
}
$('button').click(laa);

Piping createElement and appendChild in JavaScript

Can someone please explain to me, why
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
Parent.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
produces a different result from
var Node = document.createElement("testing");
var Parent = document.createElement("testingOne")
.appendChild(document.createElement("hi"));
Node.appendChild(Parent);
In the second snippet the element testingOne doesn't even get included. Why does the piping do this?
Your first example will result in
<testing><testingone><hi></hi></testingone></testing>
Parent will contain the testingOne and the hi element will be appended to it.
While the second example will result in
<testing><hi></hi></testing>
Because Parent will contain the hi element, which is returned by the appendChild method.

Beginner Javascript error with getAttribute

I've searched quite a bit on both google and stackoverflow, but a lack of knowledge on how to ask the question (or even if I'm asking the right question at all) is making it hard to find pertinent information.
I have a simple block of code that I am experimenting with to teach myself javascript.
var studio = document.getElementById('studio');
var contact = document.getElementById('contact');
var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');
var title = navLinks.getAttribute('title');
I want to grab the title attribute from the links in the element with the ID 'nav'.
Whenever I look at the debugger, it tells me that Object #<NodeList> has no method 'getAttribute'
I have no idea where I'm going wrong.
The nodetype and nodevalue for navLinks comes back as undefined, which I believe may be part of the problem, but I'm so new to this that I honestly have no idea.
The getElementsByTagName method returns an array of objects. So you need to loop through this array in order to get individual elements and their attributes:
var navLinks = nav.getElementsByTagName('a');
for (var i = 0; i < navLinks.length; i++) {
var link = navLinks[i];
var title = link.title;
}
Calling nav.getElementsByTagName('a') returns list of objects. And that list doesn't have getAttribute() method. You must call it on ONE object.
When you do:
navLinks[0].getAttribute('title')
then it should work - you will get title of the first matched element.
var navLinks = nav.getElementsByTagName('a');
getElementsByTagName returns multiple elements (hence Elements), because there can be multiple elements on one page with the same tag name. A NodeList (which is a collection of nodes as returned by getElementsByTagName) does not have a getAttribute method.
You need to access the property of the element that you actually need. My guess is that this will be the first element you find.
var title = navLinks[0].getAttribute('title');

Categories