简体   繁体   中英

Adding a div to every <span class> (Greasemonkey)

I'm about to loose my mind about this simple greasemonkey script

I want to add certain informations to an already existing with the class .grid_headline

There are 8 Instances of this .grid_headline. The problem is the loop only adds it to the last instance .grid_headline

var allHeader               = document.querySelectorAll(".grid_headline")
var anzahl_container    = document.querySelectorAll(".grid_item")
var new_div                     = document.createElement("div")
var new_div_ma              = document.createElement("div")

//Anzahl Tickets
new_div.classList.add("grid_headline_t");
new_div.innerHTML = 'Anzahl Tickets: '+ anzahl_container.length;

//Anzahl aller Spalten
new_div_ma.classList.add("grid_headline_ma");
new_div_ma.innerHTML = 'Anzahl Mitarbeiter: '+ allHeader.length;


for (var i = 0; i < allHeader.length; i++) {

    allHeader[i].appendChild(new_div);  
    allHeader[i].appendChild(new_div_ma);
}

Thanks for every kind of help.

A div can't be in more the one place in the document at the same time.

When you append it to a different element, it is no longer a child of whatever element it was a child of before.

If you want a div inside each span then you need to create a div for each span.


Aside: HTML forbids div elements being children of span elements. Consider using a different element type.

You misunderstood the other answer. What was Quentin saying is that an individual <div> created by document.createElement can only be added into one place. Instead, create the div for every place where you want to add it. That just means move the code that creates the div in the for loop:

const allHeader = document.querySelectorAll(".grid_headline");
const anzahl_container = document.querySelectorAll(".grid_item");


for (const header of allHeader) {
    const new_div = document.createElement("div");
    const new_div_ma = document.createElement("div");

    //Anzahl Tickets
    new_div.classList.add("grid_headline_t");
    new_div.innerHTML = 'Anzahl Tickets: '+ anzahl_container.length;

    //Anzahl aller Spalten
    new_div_ma.classList.add("grid_headline_ma");
    new_div_ma.innerHTML = 'Anzahl Mitarbeiter: '+ allHeader.length;

    header.appendChild(new_div);  
    header.appendChild(new_div_ma);
}

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