Access the HTML elements in JavaScript
•JavaScript•1 min read

javascripthtmlweb developmentbeginner
3 most common technique for access the HTML elements in javascript: By using ID, By using class name, By CSS selector
3 most common technique for access the HTML elements in javascript
- By using ID: for the button element we give
IDofsubmitBtn,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="submitBtn"></button>
</body>
</html>- Now we access by,
document.getElementByIdand inside the parenthesis we write theID name. - Then we set
innerHTMLfor the button as submit, it update the button text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="submitBtn"></button>
<script>
document.getElementById('submitBtn').innerHTML = 'Submit'
</script>
</body>
</html>- By using class name: in this div we give a
classname ofcontainer.
<body>
<div class="container"></div>
</body>- Then we change the background color of this div, by using
document.getElementByClassName().
<script>
document.getElementsByClassName('container')[0].style.backgroundColor = 'red'
</script>- It change the background color of the div.
- By CSS selector: here we have a image element in HTML.
<body>
<img src="" alt="">
</body>- To access this we use
document.querySelector().
<script>
document.querySelector('img').src = 'https://image_path.jpg'
</script>


