maioman
maioman

Reputation: 18762

combing querySelector() methods

I have a piece of code like this:

    document.querySelector('.wrap').style.height= lato;
    document.querySelector('.wrap').style.width= lato;

What's the syntax to combine the two objects in one?

Upvotes: 0

Views: 141

Answers (3)

Mister Epic
Mister Epic

Reputation: 16743

It is not entirely clear what you're asking. What two objects? If you are talking about not having to traverse the DOM twice to access the same element, I'd suggest caching the element after it is first accessed:

var wrap = wrap || document.querySelector('.wrap');

The first reference to wrap will ensure its value is assigned with document.querySelector(), and subsequent references will use the cached version.

wrap.style.height = lato; //Navigates through the DOM to find the element
wrap.style.width = lato; //Element is now cached, no DOM traversing needed!

Upvotes: 1

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

There actually was (still is) a syntax designed for this exact purpose or not having to type the selector twice or save it into a variable but people don't use it because it has a lot of other issues:

with(document.querySelector('.wrap')){ // don't actually do this :D
    style.height = lato;
    style.width = lato; 
    // ... all other changes
}

That's very frowned upon though, idiomatic DOM manipulation would simply cache it into a variable and call it twice saying explicitness is good here.

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You can use cssText:

document.querySelector('.wrap')
      .cssText = "height: "+lato+"; width: " + lato + ";";

Upvotes: 0

Related Questions