简体   繁体   中英

get element id using javascript

How to know which HTML element is clicked using javascript and get its ID?

I have displayed 3 labels dynamically using PHP for pagination- Page 1 , 2, 3 ,

<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(); "><?php echo $z; ?>
</a>
        </label>

Now i want that if 1 is clicked then 1-10 records are displayed , if 2 , then 11-20 and so on.For this i would run a MySQL query accordingly.

But how do i get the ID ,

Build on things that work . Start with a working link .

<a href="myScript.php?page=$z" 
   onclick="return paginationlabelclicked(this);">
      <?php echo $z; ?>
</a>

Then your script can extract the value from the href attribute or the content.

function paginationlabelclicked(element) {
    var page = element.firstChild.data;
    // …
    return false;
}

It would be a good idea to ditch the onclick attribute too .

try pass this to handler

<a href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
    </a>

and then you can access id by using

function paginationlabelclicked(el){
  alert(el.id);
  // your code
}

UPDATE

In order that to be working you have assign id to anchor

<a id="page<?php echo $z; ?>" href=# onclick="paginationlabelclicked(this); "><?php echo $z; ?>
    </a>

and then you can access id by using

function paginationlabelclicked(el){
  alert(el.id.replace('page', ''));
  // your code
}

You can easily send the id into the function called onclick, something like that:

<label id="<?php echo 'labelofpagination'.$z; ?>" value="<?php echo $z; ?>" >
<a href=# onclick="paginationlabelclicked(<?php echo $z; ?>); "><?php echo $z; ?>
</a>
</label>

I'm assuming, what you want to do is to get the text out of the <a> link that was clicked on so you can know what number the user clicked on and you can use that for your query. Here's a jQuery version:

HTML:

<label id="labelofpagination">
    <a href="#"> 1 </a>&nbsp; 
    <a href="#"> 2 </a>&nbsp; 
    <a href="#"> 3 </a>&nbsp;
    <a href="#"> 4 </a>&nbsp; 
    <a href="#"> 5 </a>&nbsp; 
</label>

Javascript:

$("#labelofpagination a").click(function() {
    // get text, trim string, convert to number
    var num = parseInt($(this).text().replace(/^\s+|\s+$/g, ""), 10);  
    // go to that page here
});

And a jsFiddle demo: http://jsfiddle.net/jfriend00/wesWd/

<a href=# onclick="paginationlabelclicked(this.parentNode); ">

...

function paginationlabelclicked(el){
  alert(el.id);
  // your code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM