DEV Community

Cover image for Understanding querySelector() and createElement() in JavaScript
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Understanding querySelector() and createElement() in JavaScript

querySelector()
The querySelector() method returns the first element that matches a CSS selector.To return all matches (not only the first), use the querySelectorAll() instead.Both querySelector() and querySelectorAll() throw a SYNTAX_ERR exception if the selector(s) is invalid.

<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The querySelector() Method</h2>
<h3>Add a background color to the first p element:</h3>
<p>This is a p element.</p>
<p>This is a p element.</p>
<script>
document.querySelector("p").style.backgroundColor = "red";
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode


Steps to create an element using DOM
To create a new HTML element using DOM you must following these steps:
Use document.createElement(), add content, set attributes and class , select the parent where the element will be insert, and Append the new element using parentChild(append means adding at the end).
//create element
const para=document.createElement('p')
//add text inside the element
para.innerText="create by using dom"
//append the element
const bodyTag=document.querySelector('body');
bodyTag.appendChild(para);

<body>
  ...
  <p>Created using DOM</p>
</body>
//Created using DOM
Enter fullscreen mode Exit fullscreen mode

Top comments (0)