Using Queryselectorall to Change the Style Property of Multiple Elements

Using querySelectorAll to change the style property of multiple elements

I would select them with a querySelectorAll and loop over them.

function changeOpacity(className) {
var elems = document.querySelectorAll(className);
var index = 0, length = elems.length;
for ( ; index < length; index++) {
elems[index].style.transition = "opacity 0.5s linear 0s";
elems[index].style.opacity = 0.5;
}
}

Edit: As a comment said you might be better off putting styling values in a CSS class if they are not dynamic and use:

elems[index].classList.add('someclass');

Updating multiple element styles using querySelectorAll

querySelectorAll() returns a collection, so you need to loop through it and call style.color on each element individually. To do this you could use forEach():

document.querySelectorAll("footer li a").forEach(function(el) {
el.style.color = Ftextlink;
});

Using document.querySelector('.').style. to change *two* CSS properties of a div

You just set the other property as well. The changes don't take effect until the browser re-renders anyway (after your JavaScript event handler has returned);

document.querySelector('.textbox').addEventListener('click', function() {
this.style.height='auto';
this.style.paddingBottom='3em';
});

Notice that you can use this to refer to the element within the handler, no need to go find it again.


However, I would recommend defining a class for this and then adding/removing it as necessary, rather than using direct style properties.

Change the style of multiple elements with the same class

var el = document.querySelectorAll('#site-nav__link-id');

for (var i = 0; i < el.length; i++) {
var currentEl = el[i];
currentEl.style.color = 'white';
}

You need to use querySelectorAll for getting multiple elements with same id.

Set CSS properties on multiple HTML elements

Yes, querySelectorAll could be used in this context. Be aware that it isn't supported in IE8 or earlier. Check out the MSN docs for some quirks.

In addition, be aware that querySelectorAll returns an array like object (a non live NodeList) so you'll have to modify your code to work with such a structure:

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 

var matched = document.querySelectorAll("#update, #save");
matched.forEach(function (c){
c.style.backgroundColor css.backgroundColor;
c.style.textDecoration = css.textDecoration;
});

Change css display of multiple elements using class in javascript

You can try the following code by adding the style 1 by 1.

function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}


Related Topics



Leave a reply



Submit