I have a static portfolio website without database, I want to count no. of products on one page and display it on another one .
Right now I have come up with this
<script>
const elements = document.querySelectorAll('.product');
const count = elements.length;
document.getElementById("Count_exec_chair").innerHTML = count;
</script>
But This only works within same page . I want to count products on 3 different pages and display them on 4th one.
(Context : It’s a small furniture company’s website , they have added 15-20 Products of 4 categories Manually in Divs using
and
Now They want me to make code so that whenever someone add product the count in menu increases .)
2
Answers
In the OP it isn’t certain how a user selects a
<div>
and how to keep track of said<div>
so the example I’ve provided uses<input type="checkbox">
as a means for the user to select an item.Each page has a
<fieldset>
– (document.forms[0].elements[0]
), and four<input type="checkbox">
– (document.forms[0].elements[1 - 4]
), and the last page has an<output>
– (document.forms[0].elements[5]
) as well.Each page has a number value assigned to variable
idx
0 to 3. Each page is also represented as an object literal:{}
stored within an array that’s stored as a string withinlocalStorage
. Each object literal has two properties:Any time a page is loaded the array of objects is retrieved from
localStorage
and the<input>
s are checked according to the object’s.selected
property (ex.[2, 3]
<input>
2 and 3 are checked). Anytime an<input>
is checked (or unchecked) the corresponding index of that<input>
is added to that page’s object.selected
array.In addition, the last page’s
<output>
will display the total sum of each object’stotal
property every time it’s loaded or if a user selects (or deslects) an<input>
.localStorage
does not function in a SO Snippet so go here for a working example.If you don’t have access to a database or server, you may be able to use
fetch()
. For instance, if you put this in the console of this page, it should show how many elements have the-link--channel-name
class on the Stack Overflow question page:Note: Please be careful when copying and pasting code into the console. Make sure you are aware of what each line of code does.
I would provide a snippet, but
fetch
can be tricky. When attempting to use a snippet, the Stack Overflow CORS policy stopped it from working.I should also mention that
fetch
will only work for you if the page you’re trying to access has the class written in the HTML. This method cannot detect a class or elements that are added after the page loads. In this instance, if I search for thes-link
class (links to questions) I get no matches.If fetch does work for your website, here is what that code does: