I'm want to change the class of a child element class based on the parent element class.
For example
<div class="change">
<div class="show-more"></div>
</div>
If parent class is class="change"
then change the child class to class="show-none"
<div class="change">
<div class="show-none"></div>
</div>
And how can I also do this to change the child id for example
<div class="change">
<div id="show-more"></div>
</div>
to
<div class="change">
<div id="show-none"></div>
</div>
How can this be done?
You can use CSS selectors and the classlist property.
If you want to do this for one element:
let el = document.querySelector('.change .show-more')
el.classList.remove('show-more')
el.classList.add('show-none')
If you want to do this for all the elements that match this selector:
document.querySelectorAll('.change .show-more').forEach(el => {
el.classList.remove('.show-more')
el.classList.add('show-none')
})
Using Javascript
<div class="change">
<div class="show-more"></div>
</div>
<script>
const allParentElement = document.getElementsByClassName('change');
const child = document.querySelector('.show-more');
for (const parentElement of allParentElement) {
if (parentElement.contains(child)) {
child.classList.add('show-none');
child.classList.remove('show-more');
}
}
</script>
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.