0

I would like to create a new element with CSS properties every time I call the squareGenerator() function, but it doesn't do that.

function squareGenerator() {
var newSquare = document.createElement("div");

this.newSquare.css({"background-color": "yellow", "height": "200px", "width": "200px"});







  $('.father').append(newSquare);
}

squareGenerator()
body{
  padding: 0;
  margin: 0;
}

.father{
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>NovaNote</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
<div class="father">

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
  </body>
</html>

1
  • Your snippet runs into an error. There are several issues: this.newSquare is different from the local var newSquare, which causes the error. Also .css is not a method of a DOM element. It looks more like a jQuery method, but you have not created a jQuery object... Commented Oct 7, 2020 at 21:17

2 Answers 2

0

Your using jQuery so do this:

var newSquare = $("<div/>");

newSquare.css({"background-color": "yellow", "height": "200px", "width": "200px"});
Sign up to request clarification or add additional context in comments.

Comments

0

In order to apply the .css() function, which is a jQuery function, you need to be operating on a jQuery object. Note in my example: $(newSquare).css().

function squareGenerator() {
   var newSquare = document.createElement("div");

   $(newSquare).css({"background-color": "yellow", "height": "200px", "width": "200px"});
   $('.father').append(newSquare);
}

squareGenerator()
body{
  padding: 0;
  margin: 0;
}

.father{
width: 100%;
height: 1000px;
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>NovaNote</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
<div class="father">

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="function.js" charset="utf-8"></script>
  </body>
</html>

Comments