Search code examples
phphtmlhtml-parsing

how to extract text from a html element by id and assign to a php variable?


I have this:

<h4 class="modal-title" id="exampleModalLabel"> hello </h4>

and I want to extract the hello word using its id and assign this to a php var but I don't have an idea. If it were an input it would be easier, but I have to use a different element.


Solution

  • you can use

    document.getElementById('exampleModalLabel').innerHTML
    

    This returns hello.

    See the fiddle

    According to the docs

    The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.

    To assign this to a php variable, please try

    <?php $text="<script>document.writeln(document.getElementById('exampleModalLabel').innerHTML);</script>";
    

    UPDATE after seeing If it were an input would be easier but I have yo use a different element in your question

    Use document.getElementById('exampleModalLabel').innerHTML to set the value of a hidden input field and then you can use it as you said in the question.