add unique id to elements inside div using javascript -
i want add unique id each paragraph element inside function 'chatsubmit' seen in below code. dom generated dynamically , paragraph has id textdisplay has different newly added dom elements.
here demo in fiddle: https://jsfiddle.net/phaneendra/89v4a7m3/
<div class="userlist"> <ul> <li onclick="openchat(this)">user1</li> <li onclick="openchat(this)">user2</li> <li onclick="openchat(this)">user3</li> <li onclick="openchat(this)">user4</li> <li onclick="openchat(this)">user5</li> </ul> </div> <div id="main"></div> function chatsubmit(form){ var sendinput = form.input; if(sendinput.value != ""){ var message = sendinput.value; var username = document.getelementbyid("username").innerhtml; document.getelementbyid("textdisplay").innerhtml += username + ": " +message + "<br/>"; sendinput.value = ""; }else{ return false; } } function openchat(username){ var user = document.createelement("div"); user.classname = "chat-app"; user.innerhtml = '<form name="form"><div class="chat-icons"><div class="username"><span id="username">'+username.innerhtml+'</span></div> <div class="settings"></div></div><div class="chat-window"><p id="textdisplay"></p></div><div class="chat-inputs"><input type="text" value="" id="input" /><input type="button" value="send" onclick = "chatsubmit(this.form)"/></div></form>'; document.getelementbyid("main").appendchild(user); }
i have updated code. please check updated code :
js :
<script type="text/javascript"> function chatsubmit(form, userid) { var pid = "textdisplay"+userid; var sendinput = form.input; if (sendinput.value != "") { var message = sendinput.value; var username = document.getelementsbyclassname(pid)[0].innerhtml; document.getelementbyid(pid).innerhtml += username + ": " + message + "<br/>"; sendinput.value = ""; } else { return false; } } function openchat(username, userid) { var pid = "textdisplay"+userid; var user = document.createelement("div"); user.classname = "chat-app"; user.innerhtml = '<form name="form"><div class="chat-icons"><div class="username"><span class='+pid+'>' + username + '</span></div><div class="settings"></div></div><div class="chat-window"><p id="'+pid+'"></p></div><div class="chat-inputs"><input type="text" value="" id="input" /><input type="button" value="send" onclick = "chatsubmit(this.form,'+userid+ ')"/></div></form>'; document.getelementbyid("main").appendchild(user); } </script>
html :
<ul> <li onclick="openchat('user1',1)">user1</li> <li onclick="openchat('user2',2)">user2</li> <li onclick="openchat('user3',3)">user3</li> <li onclick="openchat('user4',4)">user4</li> <li onclick="openchat('user5',5)">user5</li> </ul>
you can generate html storing username , id in 1 array , loop it.
please refer here
Comments
Post a Comment