DOM _Document Object Model and DOM_events

DOM _Document Object Model and DOM_events

A page is basically treated as a document and with this, we can easily change its style, content, and structure with the help of DOM.

so basically DOM provides a programming interface for web documents.

Let's suppose we want to change or give some extra style by hovering a mouse or clicking on the " P " tag of our web page then first of all we need to target that by this code snippet

const paragraphs = document.querySelectorAll("p");

Once you have the document object, you can access any element in the document using its ID or by navigating the DOM tree. For example, to access an element with the ID "myElement", you can use the following code:

javascriptCopy codevar element = document.getElementById("myElement");

You can also access elements by their tag name or class name using the following code:

javascriptCopy codevar elements = document.getElementsByTagName("div");
var elements = document.getElementsByClassName("myClass");

to change the text content of an element, you can use ==> element.textContent = "New text";

To change the style of an element, you can use the following code ==> element.style.color = "red";

let's discuss some DOM events

Here are some of the most common event types and event names:

  • Mouse Events: click, dblclick, mousedown, mouseup, contextmenu, mouseout, mousewheel, mouseover

  • Touch Events: touchstart, touchend, touchmove, touchcancel

  • Keyboard Events: keydown, keyup, keypress

  • Form Events: focus, blur, change, submit

  • Window Events: resize, scroll, load, unload, hashchange

we will see the MouseEvent

the event occurs due to user interacts with the pointing device called the mouseEvents which is nothing but MouseEvents, such as click, dblclick, mouseup, mousedown.

let's see an example where we can create a small circle on the screen were ever we click one with the mouse.

output__>

Here in the above example, I first targeted the document then I added an eventListener to it.

And inside the event listener I added a 'click' (an event name) and then the function name after a ' , ' which I want to execute when my event happens,

so in the next line, we are getting the coordinate of the screen like where we click on the screen with a new variables x and y, cont x= event.clientX; and same for "y" also.

after that, we create a new div in the body via the following code -> const circle = document.createElement('div');

and this is our 1 circle also in the body

after that we need to give it some styling and we need to make it a circle look so for that we give it a class with the following code.

circle.classList.add('circle');

now I was given some CSS to class .circle as you see in the above code.