user7213284
user7213284

Reputation: 21

Why doesn't jquery change my background-color?

The following script doesn't execute

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

Upvotes: 1

Views: 47

Answers (4)

Daniel Manta
Daniel Manta

Reputation: 6683

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>

Upvotes: 2

want2learn
want2learn

Reputation: 2511

Try this one

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

<script>
 $("#mte").css("background-color", "red");
</script>

Upvotes: 0

Jacob Birkett
Jacob Birkett

Reputation: 2125

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!

Upvotes: 0

Andy Carson
Andy Carson

Reputation: 41

<script type="text/javascript">
    document.getElementById("mte").style.backgroundColor = "red";
</script>
<body>
<div id='mte'>test 123</div>
</body>

Upvotes: 0

Related Questions