February 28, 2013

Get current HTML element in PHP

Question by Sanjay Manohar

I may have misunderstood the purpose of PHP here. But I want to do the following:

I have a PHP function, and I call it from HTML, e.g.

  <BODY>
    <DIV id='A'>
      <?php emit("hello1"); ?>
    </DIV>
    <DIV id='B'>
      <?php emit("hello2"); ?>
    </DIV>
  </BODY>      

And I want to know, within the function, which DIV it was called from.
e.g.

  <?php function emit($txt){
           echo "$txt";
           echo "from DIV id $DIVID"
        } 
  ?>

And I want it, obviously, to print

hello1 from DIV id A
hello2 from DIV id B

Is there any way of finding the “current” DIV’s ID?

Answer by Starx

Yes, you have misunderstood the purpose of PHP.

PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.

The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:

var emit = function(el, txt) {
    var id = el.attr('id');
    el.html(txt+" from DIV id "+id);

}

Now call using

emit($("#a"), "hello1");

Same can be done from JS in the following way

var emit = function(el, txt) {
    el = document.getElementById("el");    
    id = el.getAttribute('id');
    el.innerHTML(txt+" from DIV id "+id);
};

Use like:

emit("a", "hello1");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!