How to change value of parent element to an element - javascript

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";
})
}
})

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");
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++){
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>

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.

Related

Is there a way to store whatever i append to DOM with js,in local storage in order to retrieve it after page reloads?

Ok,for testing purposes lets say i have a function where it appends <li> elements inside an <ol>
container,and i want to keep all list items i've added,is there a way to store them in Local Storage (or any other way,locally) so i can retrieve them every time i reload the page ?
I've studied a little bit in Window.localStorage api,i did'nt find a method to store a dynamic element like that,but again if there is something i would'nt know to recognize the right practice to do it,since i'm still a student.Any ideas?
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored =document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color="red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored =document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
div.appendChild(inputstobestored);
inputcounter++;
}
#div{
width:600px;
}
<html>
<body>
<ol id="div">
<button onclick="addText()" style="height:100px;width:100px">ADD TEXT</button>
<button onclick="addInputs()" style="height:100px;width:100px">ADD INPUTS</button>
</ol>
</body>
</html>
Here is a working fiddle: https://jsfiddle.net/3ez4pq2d/
This function calls saveInput to save the data to localstorage. Then it also generates the
inputs that are saved via loadInput.
This just stores the ID, COLOR and WIDTH. But using this as a base you can save additional fields also.
function saveinput(obj) {
saved = localStorage.getItem("items") || "[]"
saved = JSON.parse(saved)
saved.push(obj)
localStorage.setItem("items", JSON.stringify(saved))
}
var textcounter = 1;
var inputcounter = 1;
function addText() {
var div = document.getElementById("div");
var texttobestored = document.createElement("li");
texttobestored.id = "text" + textcounter;
texttobestored.style.color = "red";
texttobestored.innerHTML = "<p>I WANT TO KEEP THIS TEXT</p>";
div.appendChild(texttobestored);
textcounter++;
}
function addInputs() {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = "input" + inputcounter;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = "blue";
inputstobestored.style.width = "600px";
saveinput({
id: "input" + inputcounter,
color: "blue",
width: "600px"
})
div.appendChild(inputstobestored);
inputcounter++;
}
function loadInput() {
inputs = localStorage.getItem("items") || "[]"
inputs = JSON.parse(inputs)
inputs.forEach(function(input) {
var div = document.getElementById("div");
var inputstobestored = document.createElement("li");
inputstobestored.id = input.id;
inputstobestored.innerHTML = "<input placeholder = ContentsToBeSaved>";
inputstobestored.style.color = input.color;
inputstobestored.style.width = input.width;
div.appendChild(inputstobestored);
inputcounter++;
})
}
loadInput();

how do i add functionality to each of the buttons?

The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>

JavaScript Creating Buttons in a loop

I want to break and center after each button, any suggestions? setAttribute did not work and does not add the breaks
for (var j = 0; j <= 6; j++) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(sm[j] + " " + sy[j]);
btn.appendChild(t);
document.body.appendChild(btn);
}
jsfiddle
HTML
<div id='theParent' class='center_the_stuff'>
</div>
JS
function addInput(type, value, name, id, onclick, parentId) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
element.id = id;
element.onclick = onclick;
var parent = document.getElementById(parentId);
//Append the element in page (in span).
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
for (var j = 0; j <= 6; j++) {
var temp = 'mybutton' + j;
addInput('button', temp, temp, temp, undefined, 'theParent');
addBreak('theParent');
}
}
CSS
.center_the_stuff {
text-align: center;
}

Removing the corresponding textbox of the anchor tag

I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}

javascript appenchild

for(var i=0; i<myJSONObject.model.length; i++){
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
create_div.innerHTML = myJSONObject.model[i].model_name;
var assign_innerHTML = create_div.innerHTML;
var create_anchor = document.createElement('a');
document.getElementById('models').appendChild(create_div);
document.getElementById(create_div.id).appendChild(create_anchor);
}
for ex the myJSONObject.model.length is 2
the output is like this
<div id = 'model_id0'>XXXXX<a> </a></div>
<div id = 'model_id1'>XXXXX<a> </a></div> */
but instead of above the output sholud be like this
<div id = model_id0> <a> xxxxxx</a></div>
<div id = model_id1> <a> xxxxxx</a></div>
how to append it inside of the innerhtml
any one plz reply !!!!
two suggestions:
1.) instead of assigning innerHTML to model_idx div assign the model name to its child a. and 2nd instead of appending it to DOM in every loop do it after completing the loop as to minimize frequent the DOM Update ie by:
objContainer = document.createElement('div');
for(....)
{
var create_div = document.createElement('div');
create_div.id = 'model_id'+i;
var create_anchor = document.createElement('a');
create_anchor.innerHTML = myJSONObject.model[i].model_name;
create_div.appendChild(create_anchor);
objContainer.appendChild(create_div);
}
document.getElementById('models').appendChild(objContainer);
I would go along the lines of:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
create_div.id = "model_id" + i;
create_div.innerHTML = "<a>" + model.model_name + "</a>";
models.appendChild(create_div);
}
Unless you specifically need to do something to the anchor itself (other than set its innerHTML), there's no need to create a reference to an element for it. If you do need to do something specific to that anchor, then in that case have this, instead:
EDIT: As per your comment, you DO want to do something to the anchor, so go with this (now updated) option - assuming the anchor will always be a child of the div that has the ID you require. The reason "model_id" + i is being put in as a string is because that is exactly what is being passed into the HTML - the document has no clue what "i" is outside of javascript:
var i = 0,
m = myJSONObject.model,
l = m.length,
models = document.getElementById("models");
for(; i < j; i++) {
var model = m[i];
var create_div = document.createElement("div");
var create_anchor = document.createElement("a");
create_div.id = "model_id" + i;
create_anchor.innerHTML = model.model_name;
if(window.addEventListener) {
create_anchor.addEventListener("click", function() {
getModelData(1, this.parentNode.id);
}, false);
} else {
create_anchor.attachEvent("onclick", function() {
getModelData(1, this.parentNode.id);
});
}
create_div.appendChild(create_anchor);
models.appendChild(create_div);
}

Categories