-1

So i've append the child to the parent (h1) and parent has class cars. When i append the child, child gets the cars style too but i don't want this to happen.

Here's my style.css:

.items{
    text-align: center;
    font-size: 10;
}

.cars{
    text-align: center;
    font-size: 70;
}

Here's the javascript code i tried:

let cars = document.createElement("h1");
cars.textContent = cars.items;
cars.classList.add("cars");

let items = document.createElement("p");
items.textContent = items.name;
cars.appendChild(items);
items.classList.remove("cars");
items.classList.add("items");

I tried so many things (like using id of cars on css) but couldn't get it right.

Shiny
  • 4,945
  • 3
  • 17
  • 33
Yousef GH
  • 3
  • 4
  • If that is all you did, `items` does _not_ have the class `cars`. Why do you think the child has the class `cars`? Also, `items.textContent = items.name;` leads me to believe your example is not your actual code. Please use the [stack snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) function to show us a [example]. – Amadan Jan 21 '20 at 06:30
  • Yes it will be applied to children elements too, because it is inheriting style from parent element [There is a explanation here](https://stackoverflow.com/a/5080452/11719787). if you want children element to some other styles then you have to apply specific styles to them separately – Sameer Jan 21 '20 at 06:34
  • The way your code is written, you will have `

    `. Why are you nesting a paragraph tag inside of a heading tag?
    – djs Jan 21 '20 at 06:51
  • Because i want to add

    under

    (as h1 is category)

    – Yousef GH Jan 21 '20 at 07:03

2 Answers2

0

You can use css combinator

.items h1{
    text-align: center;
    font-size: 10;
    }
   .cars{
    text-align: center;
    font-size: 70;
    }

check this https://www.w3schools.com/css/css_combinators.asp

Soumya Gangamwar
  • 954
  • 4
  • 16
  • 44
0

You don't have a unit of measurement for your font-size, change it to px and this worked fine for me:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <style type="text/css">
    .items{
      text-align: center;
      font-size: 10px;
    }
    .cars{
      text-align: center;
      font-size: 70px;
    }
  </style>
</head>
<body>

<script type="text/javascript">
  let cars = document.createElement("h1");
  cars.textContent = 'Cars'
  cars.classList.add("cars");
  let items = document.createElement("p");
  items.textContent = 'Items'
  cars.appendChild(items);
  items.classList.remove("cars");
  items.classList.add("items");
  document.body.appendChild(cars);
</script>
</body>
</html>

Here's a JSFiddle of it working.

Screenshot

djs
  • 3,947
  • 3
  • 14
  • 28