相关文章推荐
// Add many classes el.classList.add("this", "little", "piggy"); let classes = ["is-message", "is-warning"]; el.classList.add(...classes); // Remove a class el.classList.remove("open"); // Remove multiple classes el.classList.remove("this", "little", "piggy"); // Loop over each class el.classList; // DOMTokenList (pretty much an array) el.classList.forEach(className => { // don't use "class" as that's a reserved word console.log(className); for (let className of $0.classList) { console.log(className); el.classList.length; // integer of how many classes there are // Replace a class (replaces first with second) el.classList.replace("is-big", "is-small"); // Toggle a class (if it's there, remove it, if it's not there, add it) el.classList.toggle("open"); // Remove the class el.classList.toggle("open", false); // Add the class el.classList.toggle("open", true); // Add the class with logic el.classList.toggle("raining", weather === "raining"); // Check if element has class (returns true or false) el.classList.contains("open"); // Look at individual classes
el.classList.item(0); // hot el.classList.item(1); // dog el.classList.item(2); // null el.classList[1]; // dog

Hi , I created a loop for h2 to display 5 times but now I want to style it with a class. When I tried doing it I was only ably to get the first h2 to display the style but how can I get all 5 of them to work?

this is my code

for (var i = 0; i < 5; i++) {
    var head = document.createElement("h2");
    head.innerHTML = "Hello World";
    document.body.appendChild(head);
var style = document.createElement("div");
style.innerHTML = "h2 {font-size:20px;font-weight: lighter; font-family: sans-serif; color: cornflowerblue;}";
document.body.appendChild(style);
var css = document.querySelector("h2")
css.classList.add("border")
        

the code below will work, the correction is use classList property on your variable head not css
for (var i = 0; i < 5; i++) {
var head = document.createElement(“h2”);
head.innerHTML = “Hello World”;
document.body.appendChild(head);
head.classList.add(‘border’);

let style = document.createElement(“style”);
style.innerHTML = “.border{font-size:20px;font-weight: lighter; font-family: sans-serif; color: cornflowerblue;}”;
document.body.appendChild(style);

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

 
推荐文章