Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
call js function from php but property not found

Uncaught TypeError: Cannot read properties of null when calling js function test(). What is wrong with this example code? Is there a better way to call a js function from php for DOM Manipulation?

html

<form method="post" action="#">
    <input type="text" id="inp">Test</input>
    <button type="submit" id="submit" name="submit" value="submit"></button>
</form>

php

if(isset($_POST['submit')]
{
    $wrongInput= some code...

    if ($wrongInput)
    {
        echo "<script src=main.js></script>";
        echo "<script type=text/javascript>test();</script>"
    }
}

js

function test()
{
    document.querySelector("#submit").style.background = "red";
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Unclear where that is being echoed in the page... But for sure, the DOM needs to be loaded for the querySelector to find the element. So the use of the DOMContentLoaded event is the way to make sure, disregarding where the echo is. ;)

if(isset($_POST['submit')]
{
    $wrongInput= //some code...

    if ($wrongInput)
    {
        echo "<script src='main.js'></script>";
        echo "<script>document.addEventListener('DOMContentLoaded', test);</script>";
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!