Collarbone
Collarbone

Reputation: 610

Display the source code line number of an html tag onClick in Javascript

I want to record the source code line number for an HTML tag when I click on it. For example, if there are two tags, recording the tag alone will not help me differenciate between them.

Here is an example. Two "H1" tags:

enter image description here

When I click on the first, I want to know the source code line number:

enter image description here

If I could know that the second H1 was line number 74 (for example), I could know that the first and second H1 tags are not the same when recorded in the database.

Upvotes: 1

Views: 1672

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Best suggestion would be to get the index of the element. It's really not clear what your full intent is. If you need a complete selector to find the exact same element again that can also be done.

$('h1').click(function(){
   alert($('h1').index(this);
});

A better description of your use case would help

For a much broader all tags approach:

$('*').click(function (e) {
    if (e.target === this) { // prevent all ancestors being registered
        var tag = e.target.tagName.toLowerCase();
        var data = {
            tag: tag,
            index: $(tag).index(this);
        };
        // sending tracking data to server
        $.post('path/to/server', data);
    }
});

Upvotes: 1

AndrewL64
AndrewL64

Reputation: 16301

Why don't you add unique id names to them and detect that instead??

Something like:

HTML:

<h1 class="title" id="titleA">I'm a product designer by trade</h1>

<p>Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer.</p>

<h1 class="title" id="titleB">I'm a viking warrior by trade</h1>

<p>Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer. Lorem Ipsum is dummy text so I'm typing random paragraph texts for a StackOverflow Answer.</p>

JS:

$('#titleA').click(function(){
   alert("You clicked the first title Jamison!!");
});
$('#titleB').click(function(){
   alert("You clicked the second title Jamison!!");
});

Upvotes: 0

Related Questions