1

I'd like to check the document for a specific ID. If the ID exists, I want to change the margin of a completely different class on the same page. I'm at a loss as to why it's not working. Maybe it's not even possible?

I've tried several different versions of the same type of coding below, so I'm guessing I'm way off base...

var a = document.getElementById('CommunityTabsContainer');
var b = document.getElementsByClassName('librarysearch');
if (a != null) {
    b.style.marginTop = "-68px";
} else {
    b;
}
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • 1
    `getElementsByClassName` is a list of elements, not a single element, so you need to get the first element and change it: `document.getElementsByClassName('librarysearch')[0]` or loop over the list and change each one. – Get Off My Lawn Jun 26 '19 at 19:35
  • ...or instead of `getElementsByClassName` you could use `document.querySelector('.librarysearch')` which will get you a single element - the _first_ element that matches the selector (compared to `querySelectorAll()` which again gives you a list) -- or do you want to loop and change all matching _librarysearch_ elements? – Stephen P Jun 26 '19 at 19:39

1 Answers1

0

You're on the right track. Assuming that CommunityTabsContainer is the id you want to scan for and librarysearch is the class you want to change; you can use document.querySelector to do what you need (documented Here). I would write something like this:

const a = document.querySelector('#CommunityTabsContainer')
const b = document.querySelector('.librarysearch');

if (a !== null) {
  b.style.marginTop = '-68px'
}

Note: in your original code, getElementsByClassName returns a collection of elements, not a single element.

Shmish
  • 143
  • 5