Have been trying to get this code to work for the past 3 days and have really hit a wall. What I'm trying to do is create JS code that will retrieve article teasers within a certain topic from my home page (via class identifiers) and display them on a separate topic page (e.g. if the article is about a widget, the teaser also shows up on the Widget page).
I created a functioning code using document.getElementById, but it doesn't do what I need it to since you can only have one instance of an ID and there will be multiple articles within each topic (I've included this code for comparison for one class to simplify things). Therefore, I assume that I need either document.querySelectorAll or document.getElementsByClassName and must include code to add a div on the topic page in between each item for spacing.
Feel free to use a different approach. However, since I'm working with Visual Composer in WordPress, it needs to be Javascript. Thanks in advance for any help or suggestions!
Here's the code that works as long as you only need to select one item per topic (not the case):
window.onload = function filterContent() {
// Check browser support
if (typeof(Storage) !== "undefined") {
// Retrieve
var EV = document.getElementById("EV").innerHTML;
window.localStorage.setItem('EVId', EV);
var button =
window.localStorage.getItem('address');
document.getElementById("EV3").href = button;
} else {
document.getElementById("EV2").value = "Browser does not support Web Storage.";
}
}
Here's my revised code using document.querySelectorAll. It's not working (disappears into a huge black hole). I've tried adding a few wrinkles, such as using the Array.from property (var EVArray = Array.from(EV)), but no luck:
window.onload = function Array() {
if (typeof(Storage) !== "undefined")
{
var EV = document.querySelectorAll('.EV');
for (var i = 0; i < EV.length; i++) {
let EVId = window.localStorage.setItem('EVId', EV);
var EVResults = window.localStorage.getItem('EVId');
document.querySelectorAll('.EV2').innerHTML = EVResults;
var button =
window.localStorage.getItem('address');
document.querySelectorAll('.EV3').href = button;
}
} else {
document.querySelectorAll('.EV2').value = "Browser does not support Web Storage.";}
}
}
I have seen the following issues in your revised code:
Arrayfunction. TheArrayfunction is a reserved function name. Kindly use a different name for your function.document.querySelectorAllwill alway return a NodeList. It will never return a single element. That means you cannot directly set or get values usinginnerHTMLor other properties on the entire NodeList. In order to set or get values you will need to iterate through the NodeList and work with each individual element.Here's is the corrected version of your code: