Two ways to get other elements in div using JS

There are two ways to get other elements in a div through the JS DOM: getElementsByTagName and querySelector. The specific usage methods are as follows:

<div id="box">
        <input type="text" id="h1" value="h1">
        <input type="text" id="h2" value="h2">
</div>

How to get getElementsByTagName:

<script>
        var box = document.getElementById('box')
        var input = box.getElementsByTagName('input')[0];
        input.style.backgroundColor = 'pink'
</script>

 ('input')[0] here is because getElementsByTagName obtains a pseudo-array collection, and the event cannot be registered directly. A single element must be extracted. [0] is the index number. The renderings are as follows:

If it can be changed to [1], it is h2 to change the background. If you need to get all the input, you can use a loop 

var box = document.getElementById('box')
var input = box.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
      input[i].style.backgroundColor = 'pink'
}

 

How to obtain querySelector:

var input = document.querySelector('#box input')
input.style.backgroundColor = 'pink';

This method is commonly used in actual development and is more rigorous. However, querySelector can only get the first one. If you want to get all, you can use:

var input = document.querySelectorAll('input')
for (var i = 0; i < input.length; i++) {
     input[i].style.backgroundColor = 'pink'
}

Note: getElementsByTagName, getElementsByClassName, getElementsByName, querySelectorAll obtain pseudo array collections, and cannot directly register events. They need to add indexes at the end.

Guess you like

Origin blog.csdn.net/m0_63689815/article/details/128345578