I hope to help in your doubt. I will try to show a solution, perhaps complementary or alternative to the @pedro_andrade
, which we will create a manual script in an imperative way, since the localStorage API is simple and limited (that is, it does not equal a database, but does not take it as a criticism) so that we can incrementally save the favorito
and check all keys and check whether the URL
informed already exists.
Follow the commented script to help and try to run to see if it works as Voce wishes.
Note: the code may be cleaner and more modular, but what I want to pass is logic.
function favoritar() {
// const salvarURL = document.URL;
const salvarURL = document.querySelector('[name="url"]').value.trim();
// vamos verificar se um ID ja existe
let id = +localStorage.getItem('favId');
// caso nao exista, entao assumimos que nao existe nada salvo
if (!id) {
id = 1; // valor inicial
localStorage.setItem('favId', id); // salvamos o id no campo 'favId'
localStorage.setItem(`favorito${id}`, salvarURL); // fica: favorito1
return;
}
// o codigo seguinte server para verificar se a URL ja existe nos favoritos
let urlExiste;
for (let i = 1; i <= id; i++) {
// se o favId for 5, vamos fazer um loop de 5 iteracoes e vamos comparar
// cada uma das urls para verificar a igualdade
const url = localStorage.getItem(`favorito${i}`); // favorito1, favorito2, favorito3...
if (salvarURL === url) {
urlExiste = true;
}
}
// caso alguma url ja exista, alertamos ao usuario
if (urlExiste) {
window.alert('URL informada ja existe!');
return;
}
// caso a url informada seja valida, salvamos ela e incrementamos o favId
id = +id + 1;
localStorage.setItem('favId', id);
localStorage.setItem(`favorito${id}`, salvarURL);
}
Now let’s create a h2
with bookmarks and their respective urls.
Let’s put a div
empty html with a name class favoritos
where the bookmarks saved on localStorage will be displayed.
In html:
<div class="favoritos">
</div>
Now right after the code line localStorage.setItem(`favorite${id}`, salvarURL), let’s add the function adicionaTituloFavoritos()
where I commented so that it is explained the functioning of the code:
// ...
// invocamos a funcao toda vez que um favorito for adicionado.
adicionaTituloFavoritos();
function adicionaTituloFavoritos() {
// selecionamos a div onde serao exibidos os h2
const favoritos = document.querySelector('.favoritos');
favoritos.innerHTML = ''; // damos um reset para limpar o
// conteudo da div
for (let i = 1; i <= id; i++) {
const url = localStorage.getItem(`favorito${i}`);
// se houver uma url, vamos criar um h2
if (url) {
const h2 = document.createElement('h2');
h2.textContent = `favorito${i} - ${url}`; // texto do h2
favoritos.appendChild(h2); // adicionamos a div dos favoritos
}
}
}
I hope my code is clear and I’ve helped you.
That helped me VERY much! Thank you! Besides, I also wanted to know if it has how to (concerteza has) put all "favoritoN" in some H2, if you have 3 "favorites" it puts 3 H2 with the name of the favorite that in the case would be "favorito1", "favorito2" and "favorito3", so ok example.
– 3nder
has yes, just follow the logic to perform the loop and use methods of
document
to create a tagh2
and insert bookmarks and urls. If you want I can add this code in my reply.– Cmte Cardeal
Yes, Please! this would help me a lot and maybe help other people with the same "problem" or sla kkk.
– 3nder
added, see if my explanation helped you.
– Cmte Cardeal
Okay, I’ll test here, anything warning here whether it’s worked or not :)
– 3nder
I tested the code to add to an H2 and a part of the code is in error.

for (let i = 1; i <= id; i++) {

That part of the code, the part of<= id. i++
. In the console it says that the "id" is not defined, and I think it is because the "id" is inside another function where the variable is a "Let", (so to deduce) you can help me to solve this?– 3nder
@3nder where Voce placed the part where it adds the
h2
? it has to be placed after thelocalStorage.setItem(
favorite${id}, salvarURL);
and before closing the key}
– Cmte Cardeal
@3nder if you want I can post the complete code, because in my tests work normally. I think Voce put the function
adicionaTituloFavoritos()
outside the scope of functionfavoritar()
– Cmte Cardeal
A, true. I analyzed and it was just that, sorry kkkkkk. Thank you and bro!
– 3nder