jmj
jmj

Reputation: 145

how to get the textnode inside Div component onclick event

i have created webpage using html5 + js. I have created(thro' HTML DOM) textnodes into a div component & added it into webpage. on clicking a button event, i need that textnode value as alert.here is my code below.

<script>
var context = document.getElementById('holder');
for(j=0;j<5;j++){
var divs = document.createElement('div');
var lbl= document.createElement('label');
lbl.innerHTML = 'Hi everyone';
divs.appendChild(lbl);
var text = document.createTextNode('welcome to app');
var div = document.createElement('div');
div.appendChild(text);
divs.appendChild(div);
var btn = document.createElement('button');
btn.innerHTML ='gone';
btn.className = 'btn';
btn.id = j;
btn.onclick = function(){
var a = this.parentElement.ChildNode;
alert(a.length);
    for(i=0;i<a.length;i++)
    {
     alert(a.getElementByTagName('div').TextNode);
    }
}
divs.appendChild(btn);
context.appendChild(divs);
}
</script>

<body>
<div id='holder'></div>
</body>

Upvotes: 2

Views: 1409

Answers (2)

joequincy
joequincy

Reputation: 1395

You've got to make sure you're using the right terms. ChildNode is invalid, and the NodeList provided by childNodes does not have a getElementsByTagName function.

I'm providing a replacement for the relevant section, which has the behavior I believe you want.

var a = this.parentElement.childNodes;
for(i=0;i<a.length;i++){
    if(a[i].nodeName=="DIV"){
         alert(a[i].childNodes[0].data);
    }
}

http://jsfiddle.net/tJAde/

Upvotes: 2

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Try this.Assign an id to the button that you create and then give it onclick event!!

    var btn = document.createElement('button');
    btn.setAttribute("id", "my_id");
    document.getElementById("my_id")=onclick = function(){
    var a = this.parentElement.ChildNode;
    for(i=0;i<a.length;i++)
    {
     alert(a.getElementByTagName('div').TextNode);
    }
    }

Upvotes: 0

Related Questions