I am trying to change the css property of the "node"-class by clicking on the div inside of it which got the class "expand".
When I click on the "expand" div inside the "note", I want to go to parent "note" for changing it size:
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function () {
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" textValue
"<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for (var i = 0; i < expand.length; i ) {
expand[i].addEventListener("click", function () {
notes[i].style.size = "3000px";
})
}
})
CodePudding user response:
You can use the parentNode
attribute :
for( var i = 0; i < expand.length; i ){
expand[i].addEventListener("click", function(){
this.parentNode.style.size = "3000px";
})
}
Or the closest()
method :
for( var i = 0; i < expand.length; i ){
expand[i].addEventListener("click", function(){
this.closest(".note").style.size = "3000px";
})
}
Note that closest()
is not supported on IE.
CodePudding user response:
You have to re-get the values of expand and notes, because after you add them to your html, the two variables expand and notes, dont know yet that you have added them and they don't contain them. ( you also have to removee the eventlistner otherwise you're gonna get a bugg at approximately twelve notes added :D because you will have too many eventListners on each element
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
add.addEventListener("click", function(){
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" textValue "<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
for( var i = 0; i < expand.length; i ){
const note = notes[i];
expand[i].addEventListener("click", function() {
note.style.size = "3000px";
note.style.backgroundColor = "red";
});
}
})
#notespace {
width: 100%,
height: 100%,
background: grey,
}
<button type="button" id="add">add</button>
<input id="text"/>
<div id="notespace">
</div>