I have passed my DOM element as a string here.
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
let html = "";
notesObj.forEach(function(element, index) {
html += `<div class="noteCard card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
<a href="#" id="${index}"onclick="markNotes(this.id)"class="card-link">Important</a>
</div>
</div>`;
});
I want to give a style to the card. When an user clicks the link "Important" (as mentioned in the DOM), the corresponding card color should be changed. So I am trying to access the "noteCard" class. Here is my markNotes() function
function markNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
noteStyl = document.querySelectorAll('.noteCard')[0];
noteStyl.style.color = "red";
console.log("Color should be applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
I have tried the following things also but nothing works out.
noteStyl = document.getElementsByClassName('noteCard')[0]
noteStyl = document.querySelector('.noteCard')[0];
With this code, when I am clicking the link "Important" nothing is going to change except the printing of "Color should be applied". So there must be a problem in accessing the DOM file. I am really stuck in it. Thanks in advance
See below code and comments I added I commented your localStorage code and added my dummy code for demo.
function showNotes() {
let notes = [{
title: 'title1',
text: 'text1'
},
{
title: 'title2',
text: 'text2'
},
{
title: 'title3',
text: 'text3'
}
];
notesObj = notes;
/* if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
} */
let html = "";
notesObj.forEach(function(element, index) {
html += `<div class="noteCard card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
<a href="#" id="${index}"onclick="markNotes(this.id)"class="card-link">Important</a>
</div>
</div>`;
});
document.getElementById("html").innerHTML = html; // to insert data into HTML
}
showNotes() // calling function first time
function markNotes(index) {
console.log('index', index)
/*let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}*/
noteStyl = document.querySelectorAll('.noteCard')[index];
noteStyl.style.color = "red";
console.log("Color should be applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
//showNotes(); // See I have commented this code
}
<div id="html">
</div>