0

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 <p id ="2310">click here to set variable to 2310</p>

then in <div id="load"></div> displays 2310.

Or myVariable=targ.id; becomes id= of clicked element.

Here is code

function whichElement(e) {
var targ;
if (!e) {
var e=window.event;
}
if (e.target) {
targ=e.target;
}
else if (e.srcElement) {
targ=e.srcElement;
}
if (targ.nodeType==3) {// defeat Safari bug
targ = targ.parentNode;
}
myVariable=targ.id;
document.getElementById("load").innerHTML=myVariable;
}

<body id="-1" onmousedown="whichElement(event)">
<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>

Need to get following behavior:

If click on <p id ="2310">click here to set variable to 2310</p>

then in <div id="load"></div> displays click here to set variable to 2310.

Or myVariable=targ.id; value is clicked text.

As understand need something like this

``var myVariable = $("#???clicked id????").text();`

But do not understand how to correctly implement it in code

Please advice

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.