Solved

Detect when element is clicked and grab ID if present

Posted on 2014-11-17
5
113 Views
Last Modified: 2014-11-19
Is there a way to listen if an element of a page is clicked and then grab the ID of that element if it exists? No JQuery please, ONLY Javascript.
0
Comment
Question by:894359
  • 3
  • 2
5 Comments
 
LVL 22

Expert Comment

by:Mrunal
ID: 40449445
hi,
Here is your solution.
0
 
LVL 22

Accepted Solution

by:
Mrunal earned 500 total points
ID: 40449447
HTML code:

<div id="Div1">
    DIV 1 CONTENT</div>
<span>
    DIV 2 CONTENT no id</span>
<div id="Div3">
    DIV 3 CONTENT</div>

Open in new window


JavaScript Code:

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    if(target.id != "")
    {
        alert(target.id);
    }
    //var text = target.textContent || text.innerText;    
}, false);

Open in new window


CSS code:

div, span{
    padding: 10px;
    background-color: #CCC;
    margin: 5px;
    border: solid 2px #888;
    display: block;
}

Open in new window

0
 
LVL 4

Expert Comment

by:ItWorked
ID: 40449589
Is this what you want?
It's on fiddel

Let me know if it's not what you were looking for!
0
 
LVL 22

Expert Comment

by:Mrunal
ID: 40449735
Hi ItWorked,
Thanks for sharing your way of solution.
If we search all elements from document and then loop them and fire onclick of each of the element, it will not good for performance.
Also it will loop through all for matching particular element.
And,
if we add EventListener to document, it will be having better performance.

Also if we need to get the parent element's id then we can refer below solution:

Next Solution
0
 
LVL 4

Expert Comment

by:ItWorked
ID: 40451804
@Mrunal,
Yes you are right! And thanks for sharing your view.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show, step by step, how to integrate R code into a R Sweave document
Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question