DOM element retrieval yields inconsistent data - javascript

I have a div element which is populated with new innerHTML every time a forward or back button is clicked. But, when I use JS to store its information in a variable and console.log it I get unexpected data.
var unitName = document.querySelector("#unitName");
console.log(unitName, unitName.innerHTML.length);
The unitName will display as the current unitName, but the unitName.innerHTML.length will display the value of the previous unitName's HTML length.
Using setTimeOut will work around this and match up the apporopriate values, but is there another way to do this that doesn't involve using setTimeOut?

Related

How can I make my JS variables refer dynamically to DOM elements instead of simply saving their properties

I have a large table of <div>s on a page which get updated via JS all the time. Now I am writing a Chrome Extension to read these updates. At some point I'll have to refer to these <div> elements and their innerHTML. For some reasons, I'd rather save this whole table into one simple array, and then later update the array with the innerHTML of its elements. So I assign
savedElement = document.getElementById("ID1"); and later use console.log(savedElement.innerHtml);, However, the output is always the initiated value of the original Dom element, and never changes.
I know, when assigning a new object to a variable, the properties of the object are all copied to the variable, and future references to that variable will not output different values not matter how many times the actual DOM element has been changed.
Now, How can I save these DOM elements into my JS variables in a way that does not just keep those variables in their initiated state, but rather changes dynamically every time the DOM element is called through the variable?
console.log (dElement.innerHtml); // output Hello World
wait (3000); // this element "Obj1" is changed in the meanthile
console.log (dElement.innerHtml); // output Hello World
The problem is, as the above shows, the value of Obj1 doesn't change even if its value has been modified on the DOM itself. This output must also be synced.
Not: please let me know how to save a DOM element into a variable in a way that its innerHTML keeps updating and not just showing the initiated value.

Google App Script to Append Value from one Cell to String of Numbers in another Cell

I’ve been trying to figure out how to write a script which will take the value from one cell and append it to the end of a string of numbers in another cell of that same row. The newly appended number needs to be separated by a comma from the previously appended value, and the whole string needs to be wrapped between brackets. EX. [2,3,3,4.5,2.5,2.1,1.3,0.4]. The script will need to loop through all of the rows containing data on a named sheet beginning with the third row.
The above image is obviously just an example containing only two rows of data. The actual spreadsheet will contain well over a thousand rows, so the operation must be done programmatically and will run weekly using a timed trigger.
To be as specific as I can, what I need help with is to first know if something like the appending is even possible in Google App Scripts. I've spent hours searching and I can't seem to find a way to append a new value (ex. cell A3) to the current string (ex. cell B3) without overwriting it completely.
In full disclosure; I'm a middle school teacher trying to put something together for my school.
To be as specific as I can, what I need help with is to first know if something like the appending is even possible in Google App Scripts.
Seeing the expected result, it's inserting rather than appending, as the string should be added before the last character (]). Anyway, yes, this is possible by using JavaScript string handling methods.
Use getValue() to the get the cell values, both the Current GPA and the GPA History.
One way is to use replace
Example using pure JavaScript:
var currentGPA = 3.5
var gpaHistory = '[2,3.1,2.4]';
gpaHistory = gpaHistory.replace(']',','+currentGPA+']');
console.info(gpaHistory)
Once you get the modified gpaHistory, use setValue(gpaHistory) to add this value to the spreadsheet.

Rearrange divs by using data variables

I have the following page http://example.com (Yes, I know it's slow right now), but I need to rearrange the "dealers" under the correct states. Some of them are in the wrong location, using jquery I need to remove them and place them under the correct headers (There are no wrapping containers for each state).
I'm having a hard time doing this, how would I remove each Dealer (they have their own containers) with a data variable with the State value under the h4 with the matching state value? The data variable is data-state for each location and h4..
This will detach all of those dealerContainers, then append them back in their correct locations.
$('.dealerContainer[data-state]')
.detach()
.each(function(i,e) {
var state = $(e).data('state');
var stateh5 = $('h5[data-state='+state+']');
$(e).insertAfter(stateh5);
})

querySelectorAll to find matching data-attribute

My app uses a Parse backend to keep a running list of all the concerts in my area that my friends and I are interested in.
On the main page I use a parse query display a module for each show stored in the database. As each module is created, I use this code to add a data attribute to the show's outermost div, corresponding to the show's object ID in parse:
var showId = object.id;
$("div.show_module:last").data("showId", showId);
I'm successfully able to retrieve the showId of a specific show when the user clicks on the show's module:
$("#showsList").delegate(".showModuleBody", "click", function() {
var storeObjectId = $(this).closest("div.show_module").data("showId");
});
That all works great, proving that assigning the data-attribute is working.
Where I'm running into trouble is trying to find an element with a specific data attribute or a specific value for that attribute on a given page. The end goal is to get the y-offset of that div so I can scroll the page to the appropriate spot. I assumed I could use the following code to find the element, but it isn't working -
// find all elements with class .show_module
var allShows = document.querySelectorAll('.show_module');
// find all elements with showId data attribute
var showsWithShowId = document.querySelectorAll('[data-showId]');
// find all elements with a specific showId data attribute
var showToFind = document.querySelectorAll("[data-showId='2']");
The first of those 3 works, proving that all the elements I'm interested in are loaded into the page by the time I'm calling this function, but the 2nd and 3rd queries return nothing.
Any idea what I'm doing wrong here? Is it something with syntax? Is querySelectorAll just incompatible with how I'm setting the data attribute?
I tried to include only what I figured are the salient bits of code, but if more is necessary please let me know.
Try This
$('*[data-customerID="22"]');
For more info, look here:
Selecting element by data attribute
jQuery's .data method does not create a HTML attribute, but associates a value in its internal data store with the element.
If you want to set a data attribute with jQuery, then you need to use:
$("div.show_module:last").attr("data-showId", showId);
To get the value, you can use .data('showId') or .attr('data-showId').
(note that HTML attributes are case-insensitive, so you can also write "data-showid" instead.)

pass multidimensional javascript array to another page

I have a multidimensional array that is something like this
[0]string
[1]-->[0]string,[1]string,[2]string
[2]string
[3]string
[4]-->[0]string,[1]string,[2]string[3]string,[4]string,[5]INFO
(I hope that makes sense)
where [1] and [4] are themselves arrays which I could access INFO like myArray[4][5].
The length of the nested arrays ([1] and [4]) can varry.
I use this method to store, calculate, and distribute data across a pretty complicated form.
Not all the data thats storred in the array makes it to an input field so its not all sent to the next page when the form's post method is called.
I would like to access the array the same way on the next page as I do on the first.
Thoughts:
Method 1:
I figure I could load all the data into hidden fields, post everything, then get those values on the second page and load themm all back into an array but that would require over a hundred hidden fields.
Method 2:
I suppose I could also use .join() to concatenate the whole array into one string, load that into one input, post it , and use .split(",") to break it back up. But If I do that im not sure how to handel the multidimensional asspect of it so that I still would be able to access INFO like myArray[4][5] on page 2.
I will be accessing the arrary with Javascript, the values that DO make it to inputs on page 1 will be accessed using php on page 2.
My question is is there a better way to acomplish what I need or how can I set up the Method 2 metioned above?
This solved my problem:
var str = JSON.stringify(fullInfoArray);
sessionStorage.fullInfoArray = str;
var newArr = JSON.parse(sessionStorage.fullInfoArray);
alert(newArr[0][2][1]);
If possible, you can use sessionStorage to store the string representation of your objects using JSON.stringify():
// store value
sessionStorage.setItem('myvalue', JSON.stringify(myObject));
// retrieve value
var myObject = JSON.parse(sessionStorage.getItem('myvalue'));
Note that sessionStorage has an upper limit to how much can be stored; I believe it's about 2.5MB, so you shouldn't hit it easily.
Keep the data in your PHP Session and whenever you submit forms update the data in session.
Every page you generate can be generated using this data.
OR
If uou are using a modern browser, make use of HTML5 localStorage.
OR
You can do continue with what you are doing :)

Categories

Resources