简体   繁体   中英

How to move a div with a dynamically added class name

So currently in class we are trying to make a 15-puzzle using ONLY Javascript, CSS, and basic HTML. I am also not allowed to modify the html at all, fun stuff. Anyway, I was able to add dynamic class names to my html and reference them in the css as follows:

var children = document.getElementById("puzzlearea").childNodes;

//iterates through all children
    for (child in children) {

        //if children is a div then we do something to it
        if (children[child].nodeName == "DIV") {
            //add a class that corresponds to a css to the current div child that we are on
            children[child].classList.add('a' + i);
            i = i + 1;
        }
    }

In our CSS then we are able to reference it by simply stating .a15 and assigning it the required margin, size, image positioning, and all. However, when I try to move it by referencing its id using document.getElementById(".a15").style.top = "200px" -- or just "a15" -- it does not work. The above mentioned way is the suggestions I have seen on stack in order to move divs.

Currently I am trying something as follows:

 document.getElementsByTagName('div')[15].onclick = function () {
            alert("work"); //does actually only happen on correct div
            this.style.top = "500px" //still doesn't move it
    }

However, with this it still does not move it, and of course fetches all divs. As such, the question still stands: "How to move divs with dynamically added class names?

Edit: Got it to move by also mentioning that the position should be relative in the CSS, however I can still only reference it in the above mentioned way and not via direct iD.

You are adding class to those div(s), so when you are referencing them instead of:

document.getElementById(".a15").style.top ...

it should be:

document.getElementsByClassName("a15").style.top ... // without .

Note that getElementsByClassName returns array of elements which has that certain class. So you may have to do something like

var currentDiv = document.getElementsByClassName("a15")[0] // assuming you have only one div with class a15
// then
currentDiv.style.top ...

working example just in case: https://jsfiddle.net/Laf54y1a/3/

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