Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried quite a few things, but first, here is the HTML code.

Here is the HTML.
<div id="form">
  <input id="txtinputid" type="text" value="type"/>
  <br>
  <input type="button" onclick="newlineloop()" value="submit" />
  <input type="button" onclick="changecontent()" value="clear" />
</div>
<div id="kage">
</div>

Here is the javascript, as can be seen it takes the string from an input, and display
each letter of the string in a new div that is created.
function newlineloop() {
var txtinput = document.getElementById("txtinputid").value;

    for (i = 0; i < txtinput.length; i++)
    {
        var diviv = document.createElement("div");
        document.getElementById("kage").appendChild(diviv);
        var divclass = document.createAttribute("class");
        divclass.value = "identifier";
        diviv.setAttributeNode(divclass);
        diviv.innerHTML = txtinput[i];
    }
}


I have checked the developer tools in chrome, and i can see when you click the button that executes the newlineloop() function, it works perfectly. But i cannot change the content or delete the divs after i have created them.

My goal is to do so when you click on the button that creates the div, it will delete
the old divs from an earlier click on the button instead of just adding new
divs under the ones already created

What I have tried:

according to the w3schools DOM reference, there is not deleteElement method associated with the document object. So right now im just trying to change the content, though that is not my final goal...

I have tried to use the changecontent() function associated with one button, to change the innerHTML like this.

function changecontent() {
document.getElementsByClassName("identifier").innerHTML="work?";
}


But it does not seem to work. Also i have tried to access the div innerHTML and change the content in different parts of the code. But it will still not work.
Posted
Updated 14-Jul-18 7:45am

1 solution

From what I understood, you want the code to clear the previously created div. For instance, if the the input textbox has "type" value, click submit button, the current code will create 4 Div elements to hold each character. If user type in "abc" after that, submit, the current code will append 3 more div elements (Total 7). But you want to see 3 div element (Only abc)?

The easiest way is to clear the div container. Here is an example:

JavaScript
document.getElementById("kage").innerHTML = "";

Here is the demo: CP_clear_dom_Div - JSFiddle[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900