Selector in javascript

Element selector in javascript

Element indicates the html elements which consists of html tags and content present inside it.

How to select and change the element?

Selectors are very important, it lets javascript to access the html tags and elements. So one must know about these selectors used in javascript.

Some important selectors are explained below,

  • id selector
  • class selector

id selector in javascript (getElementById)

We can select the html element by id value using getElementById method.

It is used to access a specific element and by accessing it in javascript we can change the elements properties and its contents.

Example 1 - set background css property

Try Yourself

In the above example, we are finding the element which has value as testid and its storing elem variable.

Next by using style property of the elem variable we are change the background color of the specified element.

elem.style - using this we can change all the css properties, in this example set the background css property as red value.

Example 2 - get background css property value

Try Yourself

class selector in javascript (getElementsByClassName)

In a html document, various html elements may contain same class value, so this must be returned in an array.

Example 1 - set value by class value

Try Yourself

Example 2 - get value by class value

Try Yourself