3

This is probably just an easy question but how do i apply a css rule to a compound section instead of just to a specific id for example i currently have:

var pillpic = document.getElementById('pill');
pillpic.style.left="300px";
pillpic.style.top="160px";

How do i change this to instead be a style applied to a compound rule? like for example this:

#wrapper #photoslider #appframe #clock img {}

which if i was doing it in a stylesheet i could use

1
  • You could just use document.getElementById('clock').getElementsByTagName('IMG') Commented Dec 15, 2013 at 15:41

2 Answers 2

6

I'd suggest (in up-to-date browsers):

var images = document.querySelectorAll('#wrapper #photoslider #appframe #clock img');
[].forEach.call(images, function(a){
    a.style.top = 160px;
    a.style.left = 300px;
});

Or, rather than adjusting the style on each iteration, use CSS and add a class:

.classNameOfRelevantImages {
    top: 160px;
    left: 300px;
}

And the JavaScript to add that class:

var images = document.querySelectorAll('#wrapper #photoslider #appframe #clock img');
[].forEach.call(images, function(a){
    a.classList.add('classNameOfRelevantImages');
}

References:

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

4 Comments

You could just use pill.getElementsByTagName('IMG')
I could, but that doesn't represent the full selector, does it? And if the styles should only be applied if the entirety of those identified ancestors are present, your version wouldn't actually be correct.
first example makes a lot of sense and it is easy to understand thank you
You're very welcome indeed; I'm glad to have been of help! :)
-2

Try this,

var pillpic = document.getElementById('pill');
pillpic.className = pillpic.className + "yourclass";

or check this JavaScript CSS how to add and remove multiple CSS classes to an element

1 Comment

Then change the looks via css (#pill.yourClass{left:...})?

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.