1

The following script doesn't execute

<script type="text/javascript">
 $("mte").css("background-color", "red");
</script>
<body>
<div id='mte'>test 123</div>
</body>
  • 2
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Bugs Jun 26 '17 at 18:54

4 Answers4

2

When your script runs, the tag has not been created yet. Put your script after the div tag. Also hash symbol was missing in jQuery expression.

<div id='mte'>test 123</div>
<script type="text/javascript">
    $("#mte").css("background-color", "red");
</script>

Otherwise use $(document).ready() method, so the script will run only after page is loaded with all tags.

<script type="text/javascript">
    $(document).ready(function () {
        $("#mte").css("background-color", "red");
    });
</script>
<div id='mte'>test 123</div>
Daniel Manta
  • 5,682
  • 13
  • 35
  • 38
0
<script type="text/javascript">
    document.getElementById("mte").style.backgroundColor = "red";
</script>
<body>
<div id='mte'>test 123</div>
</body>
Andy Carson
  • 31
  • 10
0

The jQuery selector is not correct.

You should select it with this:

$("#mte")

That's to select elements with IDs. It's exactly the same as CSS. You were trying to select a list of HTML elements with the tag name mte which doesn't exist. Similarly, class selectors are preceded with a period or a full stop (.).

Full code is the following:

$("#mte").css("background": "#ff0000");

Also, if you are using the selection more than once, assign the selection to a constant.

const mte = $("#mte");
mte.css("background": "#ff0000");

See W3 School's jQuery selector guide: https://www.w3schools.com/jquery/jquery_ref_selectors.asp

Good luck!

spikespaz
  • 1,594
  • 2
  • 19
  • 42
0

Try this one

<body>
<div id='mte'>test 123</div>
</body>

<script>
 $("#mte").css("background-color", "red");
</script>
want2learn
  • 2,247
  • 2
  • 16
  • 33