javascript - How to get an H1 text inside a div through an omouseover event and innerHTML property -
i'm trying write content of h1 inside div when put mouse on h1, [object htmlheadingelement], not text itself. i'm total beginner , i'm trying innerhtml property. thank all!
html code: <h1 id="phrase" onmouseover="writeindiv2()">hi all</h1> javascript code: var text = document.getelementbyid("phrase"); function writeindiv2(){ if(div2.style.display != "none"){ div2.innerhtml = text; } }
you have 3 options text-content:
// webkit, mozilla, opera (and other standards-compliant) browsers var text = document.getelementbyid("phrase").textcontent; // microsoft internet explorer (though might have changed in ie 10) var text = document.getelementbyid("phrase").innertext; // possibly works, though assumes h1 contains text-node var text = document.getelementbyid("phrase").firstchild.nodevalue;
for efficiency, following html:
<h1 onmouseover="writeindiv2(this, 'div2')">hi all</h1> <h1 onmouseover="writeindiv2(this, 'div2')">another message</h1> <div id="div2"></div>
i'd suggest:
function writeindiv2(el, textinto){ var div2 = textinto.nodetype === 1 ? textinto : document.getelementbyid(textinto), text = el.textcontent ? el.textcontent : el.innertext; while (div2.firstchild){ div2.removechild(div2.firstchild); } div2.appendchild(document.createtextnode(text)); }
Comments
Post a Comment