Add item to an Array coming from an Htmlcollection

Asked

Viewed 253 times

0

insira o código aquiI have a HTMLCollection icon. I have the option to add a new text that comes with a new icon, in case increasing this HTMLCollection. need to make a ForEach() on it to give 'life' to that button, I want it to hide or show the text.

So I did:
Array.from('taldohtmlcollection').forEach

okay.

The question is when I add new text with a new icon. This new icon is added to HTMLCollection, however the Array does not update, that is, continues with the old items and does not receive this new icon. I need to fix this, so that it iterates between all the items of Array, and add a new icon HTMLCollection, it also passes to Array.
I hope I was clear.

<!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">
    <link rel="stylesheet" href="stylenote.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
        integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <title>Document</title>
</head>

<body>
    <div id="container0">
        <header>
            <h1>Note Manager</h1>
            <form action="">
                <input id="searchbar" type="text" placeholder="Search">
            </form>
        </header>
        <main>
            <div id="notes">
                <ul>
                    <li class="linotes">
                        <a class="clickicon"><i class="fas fa-edit"></i></a>
                        <p class="titleofnotes">First Note</p>
                        <input type="text" class="inputnote" value="">
                    </li>
                    <li class="linotes">
                        <a class="clickicon"><i class="fas fa-edit"></i></a>
                        <p class="titleofnotes">Second Note</p>
                        <input type="text" class="inputnote" value="">
                    </li>
                    <li class="linotes">
                        <a class="clickicon"><i class="fas fa-edit"></i></a>
                        <p class="titleofnotes">Third Note</p>
                        <input type="text" class="inputnote" value="">
                    </li>
                </ul>
            </div>
            <div id="hide-notes">
                <label for="hide">Hide Notes</label>
                <input id="hide" type="checkbox">
            </div>
            <div id="addnotes">
                <label for="add">Add Note</label>
                <input id="add" type="text">
                <input type="submit" value="Add" id="btnadd">
            </div>
        </main>
    </div>
</body>
<script src="notejs.js"></script>

</html>
 CSS
body{
    font-family: Arial, Helvetica, sans-serif;
}
ul{
    margin: 0;
    padding: 0;
    list-style:none;
}
#container0{
    margin:0%  20%;
    background-color:floralwhite;
} 
header{
    padding:5%;
    text-align: center;
    background-color: #cccccc;

}
header input{
    width: 28%;
}
#notes{
    margin-left: 5%;
    margin-bottom: 10%; 
}
li input {

 width: 85%;
}
#hide-notes label{
    user-select: none;
}
#hide-notes label:hover{
 background-color:#ccccff 
}

#hide-notes input[type="checkbox"]{
display: none;


}
#addnotes{
    text-align: center;
}
#btnadd{
    background-color:rgb(13, 131, 48);
    color: white;
    width: 8%;
    height: 30px;
    border-radius: 10px;
    font-size:16px; 
}
.clickicon{

    float: right;
    cursor: pointer;
    margin-right: 5%;

   var lista = document.querySelector("ul");
   var btnadd = document.getElementById("btnadd");
   var addinput = document.getElementById("add");
   btnadd.addEventListener('click', function (e) {

    e.preventDefault();
    if (addinput.value !== '') {
        var newli = document.createElement("li");
        var plist = document.createElement("p");
        var inputlist = document.createElement("input");
        var clickicon = document.createElement("clickicon");
        var icon = document.createElement("i");
        clickicon.className = 'clickicon';
        icon.className = 'fas fa-edit';
        lista.appendChild(newli);
        newli.appendChild(clickicon);
        clickicon.appendChild(icon);
        newli.appendChild(plist);
        plist.className = "titleofnotes";
        newli.appendChild(inputlist);
        inputlist.setAttribute("type", "text");
        plist.textContent = addinput.value;


var searchbar = document.getElementById('searchbar');
var linotes = document.getElementsByClassName('linotes');
var searchbar.addEventListener('keyup', function (e) {
    text = e.target.value.toUpperCase();
    Array.from(linotes).forEach(function (note) {
        console.log(note)
        var litextp = note.textContent;
        var capslitextp = litextp.toUpperCase();
        if (capslitextp.indexOf(text) > -1) {
            note.style.display = 'block'
        }
        else { note.style.display = 'none' }
    })
})

2 answers

1


You’ll have to rotate the Array.from( variavel ) again, another option is you also add the value in the variable that was generated with the Array.from.
When you call the Array.from you are creating a new Array.
See the example below.

var arrayA = [1,2,3],
    arrayB = Array.from(arrayA),
    arrayC = Array.from(arrayA);
    
console.log('START', 
    'A:',JSON.stringify(arrayA),
    'B:',JSON.stringify(arrayB),
    'C:',JSON.stringify(arrayC));
    
console.log('mudei o original `arrayA`')
arrayA.push(4);
console.log('TESTE 1',  
    'A:',JSON.stringify(arrayA),  /// mudou
    'B:',JSON.stringify(arrayB),  /// nada aconteceu com esse
    'C:',JSON.stringify(arrayC)); /// nada aconteceu com esse
    
console.log('mudei o secundario `arrayB`')
arrayB.push(5);
console.log('TESTE 2', 
    'A:',JSON.stringify(arrayA), /// continua igual ao TESTE 1
    'B:',JSON.stringify(arrayB), /// mudou
    'C:',JSON.stringify(arrayC)); /// nada aconteceu com esse

I don’t know how this your code, but I think you can try to do something as shown in the example below.

/// faz com que ao clicar no button chame a funcao addElem;
document.getElementsByTagName('button')[0].onclick = addElem;

/// Funcao para adicionar um novo elemento
function addElem(){
    var novoElem = document.createElement("div"); /// Cria uma div
    novoElem.className = 'elem'; /// coloca a classe como `elem`
    
    /// busca o elemento de class='base' 
    ///   e adiciona o novo elemento como filho
    document.querySelector('.base').appendChild( novoElem );
    
    /// Busca pela class='.elem' e retorna um array com os elementos
    var array = getElemArrayByQuery('.elem');
    
    /// coloca como texto do novo elemento o tamanho atual da array
    novoElem.innerText = array.length;
    
    console.log( array );
    
    /// posso fazer o forEach aki
    //array.forEach(function(elem,idx){
    //		console.log(idx,elem);
    //})
}

function getElemArrayByQuery(cls){
    /// querySelectorAll retorna um HTMLColletion com os resultados
	var collection = document.querySelectorAll(cls);
    /// Criar um Array com base no HTMLCollection e retorna
	return Array.from( collection );
}
<html>
<bod>
  <div class='base'>
      <div class='elem'>1</div>
  </div>
  <button>
  adicionar icon
  </button>
</bod>
</html>

  • I’ll edit and upload the code. the new element added to Htmlcollection, not me, is automatic depends on whether the user clilcates to open a new note. comes with the icone of the same class. Adding an item.

0

The best solution I could find is to use the Bubbling Event to my advantage. I’ve studied a little bit more. The way is to use the larger element as the .

 ul = document.QuerySelector('#div ul')
 ul.EventListener(click, function(e){
   if (e.target.ClassName == 'classe do icone'){
      e.target.parentElement = li  //Pegando o li
      li.parentElement.removeChild(li); //passando pro Ul pra usar remove child e deletando o li 

} })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.