简体   繁体   中英

why is my element only appending to one class?

I've been trying to dynamically append a div to inside multiple other divs:

SoundCloudAPI.renderTracks = function createCards(){
    var card = document.createElement('div');
    card.classList.add("card");

    var searchResults = document.querySelector('.js-search-results');
    searchResults.appendChild(card);

    var imageDiv = document.createElement('div');
    imageDiv.classList.add("image");

    var imageResults = document.querySelector('.card');
    imageResults.appendChild(imageDiv);
}

however, it only appends to the first "card" div in my body.

What's the problem here?

querySelector will return the first element with this class, so you have to use querySelectorAll , then loop throught the found element using foreach to append you element as below

SoundCloudAPI.renderTracks = function createCards(){
    var card ;

    var searchResults = document.querySelectorAll('.js-search-results');
    // loop using foreach
    searchResults.forEach(function(searchResult) {
       card = document.createElement('div');
       card.classList.add("card");
       searchResult.appendChild(card);
    });

    var imageDiv;

    var imageResults = document.querySelectorAll('.card');
    // loop using foreach
    imageResults.forEach(function(imageResult) {
        imageDiv = document.createElement('div');
        imageDiv.classList.add("image");
        imageResult.appendChild(imageDiv);
    });

}

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