Skip to content Skip to sidebar Skip to footer

Click On Text And Set/define The Text As Value Of Javascript Variable

Example is based on this answer https://stackoverflow.com/a/7132830/2465936 Here is working example http://jsfiddle.net/rigaconnect/aGWGn/3/ If click on

click h

Solution 1:

HTML:

<body id="-1">

<p id="3.14">click here to set variable to 3.14</p>
<h3 id="5">click here to set variable to 5</h3>
<p id ="2">click here to set variable to 2</p>
<p id ="2310">click here to set variable to 2310</p>

<div id="load"></div>

JS:

document.body.onmousedown = whichElement;
var output = document.getElementById("load")
function whichElement(e) {
    e = e || window.event;
    var targ = e.target || e.srcElement;
    if (targ.nodeType===3) {// defeat Safari bug
        targ = targ.parentNode;
    }
    output.innerHTML = targ.innerHTML;
}

DEMO: http://jsfiddle.net/aGWGn/5/

Note: If I remember it well, in HTML5 an id can be what you want, but before HTML5 it should start with a letter, not number.


Post a Comment for "Click On Text And Set/define The Text As Value Of Javascript Variable"