-2

Hy all i m facing the issue regarding getelement by className it didnt work in my vs code also document.queryselectorAll didnt work i have checked so many times but nothing work can you guys please look at the code and guide me thank you all

<body>

<div class="div">
    <h2>heading</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, esse.</p>
    <button>submit</button>
</div>

<div class="div">
    <h2>heading</h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ex, esse.</p>
    <button>submit</button>
</div>


<script>
    let m = document.getElementsByClassName('div').style.margin = "200px"

</script>

2 Answers2

1

document.getElementsByClassName('div') returns a NodeList, and not a single element. You will need to loop through the result, and change the style for each element.

let divs = document.getElementsByClassName('div');
for (let i = 0; i < m.length; i++) {
  divs[i].style.margin = "200px"
}
BaseScript
  • 381
  • 2
  • 7
0

the document.getElementsByClassName('div') returns an array containing the elements. you should pass an index for example document.getElementsByClassName('div')[0] or if you want the style to apply to all the divs you can map it.

document.getElementsByClassName('div').map((element)=>{
element.style.margin = "200px"
return element
})