Unable to access the DOM which I passed as a string. How to do it by using external function as I defined in the code?

青春壹個敷衍的年華 提交于 2020-08-10 19:17:44

问题


I want to add an event to the "Important" link i.e. When One user clicks the "Important" link, the corresponding card color should be changed and saved in the localstorage but, when I am accessing that DOM file which I passed as a string, I am unable to do it. For e.g. - I can't access to document.getElementsByClassName("noteCard") in function markNotes(index). But at the same time console.log("Color is not applied") executes successfully. If I am adding document.body.style.backgroundColor = "lightblue"; then also body color changes accordingly, but the I want to change the background color of the card with class "noteCard" only. I am really stuck with it.

Below is my HTML code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Magic Notes</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="Customstyle.css">

</head>

<body>
    <nav class="navbar navbar-expand-lg navbar navbar-dark bg-dark">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarTogglerDemo01">
            <a class="navbar-brand" href="#">Magic Notes</a>
            <ul class="navbar-nav mr-auto mt-2 mt-lg-0">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="https://www.facebook.com/balabhadra.chand/" target="_blank">About me</a>
                </li>

            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" id="searchTitle" type="search" placeholder="Search by title" aria-label="Search">
            </form>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search text" aria-label="Search">
                <button class="btn btn-outline-success my-2 my-sm-0 " id="searchBtn" type="submit">Search</button>
            </form>
        </div>
    </nav>
    <h1 class="heading">It's all about magic !!!</h1>
    <div class="card" style="width: 1000px;">

        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">Add a title to your note</textarea></span>
            </div>
            <textarea class="form-control" id="addTitle" aria-label="With textarea"></textarea>
        </div>

        <div class="card-body">
            <form>
                <div class="form-group">
                    <label for="exampleFormControlTextarea1">Write your Note</label>
                    <textarea class="form-control" id="addTxt" rows="3"></textarea>
                </div>
            </form>

            <button class="btn btn-primary" id="addBtn">ADD NOTE</button>
        </div>

    </div>
    <hr>
    <h5>Your Notes</h5>
    <hr>
    <div id="notes" class="row container-fluid"></div>


    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    <script src="myscript.js"></script>
</body>

Here is my JavaScript code

console.log('MagicNotes')
showNotes();

let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function(e) {
    let addTxt = document.getElementById("addTxt");
    let addTitle = document.getElementById("addTitle");
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    let myObj = {
        title: addTitle.value,
        text: addTxt.value
    }
    notesObj.push(myObj)
    localStorage.setItem("notes", JSON.stringify(notesObj));
    addTxt.value = "";
    addTitle.value = "";
    showNotes();
});

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>`;

    });
    let notesElem = document.getElementById("notes");
    if (notesObj.length != 0) {
        notesElem.innerHTML = html;
    } else {
        notesElem.innerHTML = `Please add a note by clicking "ADD NOTE"`;
    }
}

function deleteNotes(index) {
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    notesObj.splice(index, 1);
    localStorage.setItem("notes", JSON.stringify(notesObj));
    showNotes();
}

function markNotes(index) {
    let notes = localStorage.getItem("notes");
    if (notes != null) {
        notesObj = JSON.parse(notes);
    } else {
        notesObj = [];
    }
    document.getElementsByClassName("noteCard").style.color = "lightblue";
    console.log("Color is not applied")
    localStorage.setItem("notes", JSON.stringify(notesObj));
    showNotes();
}

let searchText = document.getElementById('searchTxt');
searchText.addEventListener("input", function(txt) {

    let inputVal = searchText.value.toLowerCase();
    // console.log('Input event fired!', inputVal);
    let noteCards = document.getElementsByClassName('noteCard');
    Array.from(noteCards).forEach(function(element) {
        let cardTxt = element.getElementsByTagName("p")[0].innerText;
        if (cardTxt.includes(inputVal)) {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
        // console.log(cardTxt);
    })
})
let searchTitle = document.getElementById('searchTitle');
searchTitle.addEventListener("input", function(title) {

    let inputValTitle = searchTitle.value.toLowerCase();
    let noteCardsTitle = document.getElementsByClassName('noteCard');
    Array.from(noteCardsTitle).forEach(function(element) {
        let cardTitle = element.getElementsByTagName("h5")[0].innerText;
        if (cardTitle.includes(inputValTitle)) {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
        // console.log(cardTitle);
    })
})

回答1:


You were missing index while fetching element inside markNotes:

function markNotes(index) {
   let notes = localStorage.getItem("notes");
   if (notes != null) {
    notesObj = JSON.parse(notes);
   } else {
    notesObj = [];
   }
  let noteCard = document.getElementsByClassName("noteCard")[index];
    noteCard.style.color = "lightblue";
    console.log("Color is applied")
   localStorage.setItem("notes", JSON.stringify(notesObj));
   //showNotes(); you don't need to add this again
}

complete working code fiddle link



来源:https://stackoverflow.com/questions/62984663/unable-to-access-the-dom-which-i-passed-as-a-string-how-to-do-it-by-using-exter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!