简体   繁体   中英

Assigning CSS ID to Javascript Created Element

So I'm trying to create Dynamic Content for a HTML page, using JavaScript to create elements based on click events, which would be affected by pre-existing CSS styling.

But I can't seem to hook the new element to it's CSS ID.

crestDiv.onclick = function()
{
    //Remove the Elements on Screen
    var element = document.getElementById("crestDiv");
    element.parentNode.removeChild(element);
    element = document.getElementById("breakDiv");
    element.parentNode.removeChild(element);
    element = document.getElementById("buildDiv");
    element.parentNode.removeChild(element);
    element = document.getElementById("surgeDiv");
    element.parentNode.removeChild(element);
    element = document.getElementById("wavesIcon");
    element.parentNode.removeChild(element);

    //Add the Elements to Screen

    //Create Heading
    var heading = document.createElement("h1");
    heading.id = "crestTitle";
    var node = document.createTextNode("Crest Heading");
    heading.appendChild(node);

    //Attach Heading to existing Element
    element = document.getElementById("contentDiv");
    element.appendChild(heading);
}

It works, the heading appears on the screen after all the rest of the content disappears, but it has no CSS styling on it.

You can see I'm trying to use the CSS ID of "crestTitle" to apply to the new Heading, but no matter what styling I put under #crestTitle in my CSS sheet, it doesn't affect the new heading.

Am I making any obvious errors?

Can you provide a jsfiddle including your HTML and CSS as well? This works for me: https://jsfiddle.net/nw35g21x/

CSS:

#crestDiv{
  width:100%;
  min-height:100px;
  background-color:cyan;
}

#crestTitle{
  color:red;
}

HTML:

<body>
<div id="contentDiv">
<div id="crestDiv">

</div>
</div>
</body>

JavaScript:

var crestDiv = document.getElementById("crestDiv");
crestDiv.onclick = function()
{
    //Remove the Elements on Screen
    var element = document.getElementById("crestDiv");

    //Add the Elements to Screen

    //Create Heading
    var heading = document.createElement("h1");
    heading.id = "crestTitle";
    var node = document.createTextNode("Crest Heading");
    heading.appendChild(node);

    //Attach Heading to existing Element
    element = document.getElementById("contentDiv");
    element.appendChild(heading);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM