1

Another Newbie Question: I am attempting to completely remove a class from the DOM when the screen.width is smaller than or equal to 320 px. Attempting this without specifying a screen width works just fine. The class is removed from the page, but when I attempt to specify the conditional screen width it does not. Can anyone help me out here? This is what I have:

<div class="poison">Poison Text</div>

<script>
var p = document.getElementsByClassName('poison');
var cstr = "poison";
var poison = screen.width;

if (poison <= 320) {
    (var i = p.length; --i >= 0;) {
        var n = p[i];
        while (n.className.split(" ").indexOf(cstr) == -1) {
            n = n.parentNode;
        }
        n.parentNode.removeChild(n);
    }
}
</script>
4
  • 4
    It looks like you tried to write a for loop (var i = p.length; --i >= 0; ) and forgot the for Commented Jul 25, 2014 at 15:28
  • What is (var i=p.length; --i>=0;) supposed to be doing? Is this an if statement? A for loop? In its current state this snippet of code will not achieve anything. Commented Jul 25, 2014 at 15:28
  • You should have your developer console open while testing your code. Commented Jul 25, 2014 at 15:32
  • ...also, I don't see the purpose of the while loop. You already know that the n element has that class, so why attempt to traverse through its ancestors? Commented Jul 25, 2014 at 15:34

1 Answer 1

2

You should use media queries instead of JS for this. Add this line to your stylesheet

@media (min-width:320px){


}

and put the class/classes you wish to use at sizes above 320px inside.

You can use max-width and multiple conditions as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Doing it with a media query removes it from sight but the element still exists and takes up space. I would like to use javascript to remove it from the DOM thus making the space available on the page when rendered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.