简体   繁体   中英

JS es6 on click add class to another element

I'm trying to show a div when another button has been clicked.

Unfortunately the site i'm using doesn't use jquery but has babel.js installed.

This is the HTML of the button the user is clicking

<button id="ba-Calculate" class="button">Calculate</button>

And this is the HTML for the button I would like to display

<button class="js-find-a-mortgage button u-margin-top-small" style="display: none;">Find a mortgage</button>

I've added a style of display none to hide the element.

This is what i've come up with so far.

var el = document.querySelector('#ba-Calculate');

el.onclick = function() {
document.getElementsByClassName('js-find-a-mortgage').style.display = 'block';
}

Any suggestions or where to read up on how I can crack this would be great.

I appreciate the feedback, thank you.

document.getElementsByClassName returns an array. So, you need to fetch the first element (I believe you have only one element with that class in the DOM) and add the style.

Try using

document.getElementsByClassName('js-find-a-mortgage')[0].style.display = 'block';
var trigger = document.querySelector('#ba-calculate')
var el = document.querySelector('.js-find-a-mortgate')

trigger.addEventListener('click', function () {
  el.style.display = 'block'
})

getElementsByClassName returns an array like object

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

Using querySelector will grab the first instance of a node matching that class name. You can then use the code you already had.

If you want to add class, I assume you need to use classList method add :

For example to add for your element class 'hidden': document.getElementsByClassName('js-find-a-mortgage')[0].classList.add('hidden');

To see all classes use: document.getElementsByClassName('js-find-a-mortgage')[0].classList

https://www.w3schools.com/jsref/prop_element_classlist.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM