I have added HTML5 buttons & text in a webpage thro' DOM methods. What i need is, when i clicked a particular button, it's corresponding Btn_ID & corresponding text should be shown in alert. I am getting corresponding Btn_ID, but i'm not able to take its text.
My Code is;
<head>
<style>
.tbls {
height:60px;
width:100%;
}
.Rows {
height:60px;
width:100%;
background-color:lightblue;
}
.Btn {
height:40px;
width:70px;
}
</style>
</head>
<body>
<div id='contnt'></div>
</body>
<script>
var arry = ["Name 1", "Name 2", "Name 3", "Name 4", "Name 5"];
var container = document.getElementById('contnt');
for(var j = 0; j < arry.length; j++) {
var tbls = document.createElement('table');
tbls.className = 'tbls';
var Rows = document.createElement('tr');
Rows.className = 'Rows';
var Column = document.createElement('td');
var questionlist = document.createTextNode(arry[j]);
Column.appendChild(questionlist);
var Btn = document.createElement('button');
Btn.id = j;
Btn.className = 'Btn';
Btn.innerHTML = 'SUBMIT';
Btn.onclick = function () {
alert(this.id);
alert(this.parentElement.questionlist);
}
Column.appendChild(Btn);
Rows.appendChild(Column);
tbls.appendChild(Rows);
container.appendChild(tbls);
}
</script>
Code example: http://jsfiddle.net/DerekL/9je7N/
Do you mean you want to alert
Name1 if the first submit
is clicked?
Btn.onclick = function() {
alert(this.id);
alert(this.parentElement.firstChild.nodeValue);
}
//this.parentElement = Your table cell
//this.parentElement.firstChild = text node (questionlist)
//this.parentElement.firstChild.nodeValue = text node's value //Name1, Name2
Update:
To get the first text node within the td
element
Btn.onclick = function() {
alert(this.id);
var children = this.parentElement.childNodes;
var text;
for(var i = 0; i < children.length; i ++) {
if(children[i].nodeType === Node.TEXT_NODE) {
text = children[i].nodeValue;
break;
}
}
alert(text);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.