How to Access an Element in HTML DOM using JavaScript?

Element Access Methods

MethodDescription
document.getElementById(“ID”)Get the element with the specified ID
document.getElementsByTagName(“Tag_Name”);Get all the specified element by the Tag Name
document.getElementsByClassName(“Class_Name”);Get all the specified element by the Class Name
document.querySelector(“CSS_Selector”);It returns the first match of the passed selector string
document.querySelectorAll(“CSS_Selector”);It returns a node list of DOM elements that match the query

getElementById(“ID_Name”)

The method getElementById(“ID_Name”) returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

getElementsByTagName(“Tag_Name”)

The method getElementsByTagName(“Tag_Name”) returns a live node list meaning that it updates itself with the DOM tree automatically, so modification of the DOM tree will be reflected in the returned collection. The returned Node List or Collection of Nodes can be accessed by index numbers starting with index 0.

  • This method accepts a string indicating the type of elements that be retrieved, a special value “ * ” returns all elements in the documents.
  • You can use the length property of the NodeList object to determine the number of elements with the specified tag name, then you can loop through all elements and extract the info you want.

getElementsByTagName(“Tag_Name”)

getElementsByTagName(“Tag_Name”)

More specific

getElementsByTagName(“Tag_Name”)

  • Length Property
  • Loop

getElementsByClassName(“Class_Name”)

The Method getElementsByClassName() returns a live node list meaning that it updates itself with the DOM tree automatically, so modification of the DOM tree will be reflected in the returned collection. The returned Node List or Collection of Nodes can be accessed by index numbers starting with index 0.

•This method accepts string indicating the class name of elements that be retrieved •

We can also pass multiple class name. For matching, all the class names should match. •You can use the length property of the NodeList object to determine the number of elements with the specified class name, then you can loop through all elements and extract the info you want.

  • This method accepts string indicating the class name of elements that be retrieved
  • We can also pass multiple class name. For matching, all the class name should match.
  • You can use the length property of the NodeList object to determine the number of elements with the specified class name, then you can loop through all elements and extract the info you want.

getElementsByClassName(“Class_Name”)

getElementsByClassName(“Class_Name”)

More specific

getElementsByClassName(“Class_Name”)

  • Length Property
  • Loop
Tagged : / / /

Which Array Functions are present in Array

  • array_change_key_case — Changes the case of all keys in an array
  • array_chunk — Split an array into chunks
  • array_column — Return the values from a single column in the input array
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge two or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the first corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user supplied function to every member of an array
  • array — Create an array
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key_exists — Alias of array_key_exists
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive “natural order” algorithm
  • natsort — Sort an array using a “natural order” algorithm
  • next — Advance the internal pointer of an array
  • pos — Alias of current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Alias of count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function
Tagged : / / / / /

What is the use of the document object model in JavaScript?

Document Object Model

  • The Document Object Model (DOM) is an Application Programming Interface (API) for HTML and XML documents.
  • With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content.
  • The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.
  • The DOM model represents a document with a logical tree.
  • According to Document Object Model (DOM), every HTML-tag is an object. Nested tags are called “children” of the enclosing one. All operations on the DOM start with the document object. From it, we can access any node.
  • The Document Object Model can be used with any programming language.

DOM Levels

  • DOM Level 0 – This level supports the common document object collections – form[ ], image[ ], anchors[ ], links[ ] and applets[ ]. This is also known as classic or traditional JavaScript Object Model. •
  • DOM Level 1- It provides the ability to manipulate all elements in a document through a common set of functions. In this level, all elements are exposed and parts of the page can be read and written to at all times.
  • DOM Level 2 – It provides further access to page elements primarily related to CSS and focuses on combining Level 0 and Level 1 while adding improved support for working with XML documents.

DOM Levels

  • DOM Level 3 – Enhanced Level of Level 1 and Level 2 and added support for XPath and keyboard event handling.
  • DOM Level 4 – Enhanced  year 2015

Categories of DOM

  • DOM Core – It specifies a generic model for viewing and manipulating a marked-up document as a tree structure.
  • DOM HTML – It specifies an extension to the core DOM for use with HTML. This represents DOM Level 0 with capabilities for manipulating all of the HTML element objects.
  • DOM CSS – It specifies the interfaces necessary to manipulate CSS rules programmatically.
  • DOM Events – It adds event handling to the DOM.
  • DOM XML – It specifies an extension to the Core Dom for use with XML.

Document Tree

DOM Node Types

ConstantNode TypeDescription
Node.ELEMENT_NODE1An element such as <h1> or <div>
Node.TEXT_NODE3The actual Text of Element or Attribute ex: – “Hello”
Node.PROCESSING_INSTRUCTION_NODE7An instruction to a parser on aspect of the document <?xml version=“1.0”?>
Node.COMMENT_NODE8A comment such as < – – Something – – >
Node.DOCUMENT_NODE9A Document Node
Node.DOCUMENT_TYPE_NODE10A doctype statement <!DOCTYPE html>
Node.DOCUMENT_FRAGMENT_NODE11A document fragment, which represents a lightweight structure to hold a collection of DOM nodes for manipulation or insertion.

Node Relationship

  • Parent
  • Children
  • First Child
  • Previous Sibling
  • Next Sibling
  • Last child

DOM Node Properties

PropertiesDescription
nodeNameContains the name of the node
nodeValueContains the value within the node; generally only applicable to text nodes
nodeTypeHolds a number corresponding to the type of node
parentNodeReference to the parent node of the element, if one exists
childNodesAccess to the list of child nodes
firstChildReference to the first child node of the element, if one exists
lastChildPoints to the last child node of the element, if one exists
previousSiblingReference to the previous sibling of the node; for example, if its parent node has multiple children
nextSiblingReference to the next sibling of the node; for example, if its parent node has multiple children
attributesThe list of the attributes for the element
ownerDocumentPoints to the HTML Document object in which the element is contained

Tagged : / / /

How do you use a date object in JavaScript?

Date

The Date object provides a sophisticated set of methods for manipulating dates and times.

• It reads client machine date and time so if the client‟s date or time is incorrect, your script will reflect this fact.
• Days of week and months of the year are enumerated beginning with zero.
0 – Sunday, 1 – Monday, and so on
0 – January, 1 – February, and so on
• Days of the month begin with One.

Creating Date Object

Date objects are created with the new Date() constructor. Date Objects created by programmers are static. They do not contain a ticking clock.

Syntax:-

Creating Date Object

  • new Date( ) – new Date() creates a new date object with the current date and time.

Creating Date Object

  • new Date(milliseconds) – It creates a new date object as January 1, 1970, 00:00:00 Universal Time (UTC).

Ex: –

Creating Date Object

  • new Date(year, month, day, hours, minutes, seconds, milliseconds) It creates an object with the date specified by the integer values for the year, month, day, hours, minutes, second, milliseconds. You can omit some of the arguments.

Month and Week Day start with 0
0 – Sunday
0 – January
Month Day starts with 1
1 – 1

Creating Date Object

No. of argumentsDescription (in order)
7year, month, day, hour, minute, second, millisecond
6year, month, day, hour, minute, second
5year, month, day, hour, minute
4year, month, day, hour
3year, month, day
2year and month
1Millisecond

Creating Date Object

  • new Date(dateString) – new Date(dateString) creates a new date object from a date string.

Ex: –
var tarikh = new Date(“May 12, 2018 10:16:05″)

Date TypeFormatExample
ISO DateYYYY-MM-DD“2018-06-21” (The International Standard)
Short DateMM/DD/YYYY“06/21/2018″
Long DateMMM DD YYYY“June 21 2018 or “21 June 2018″

ISO Dates

ISO 8601 is the international standard for the representation of dates and times.

DescriptionFormatExample
Year and MonthYear and Month2018-06
Only YearYYYY2018
Date and TimeYYYY-MM-DDTHH:MM: SSZ2018-06-21T12:00:00Z
Date and TimeYYYY-MM-DDTHH:MM:SS+HH: MM
YYYY-MM-DDTHH:MM:SS-HH: MM
2018-06-21T12:00:00+06:30
2018-06-21T12:00:00-06:30

Date and Time are separated with a capital T.
UTC time is defined with the capital letter Z.
If you want to modify the time relative to UTC, remove the Z and add +HH: MM or -HH: MM instead.

Short Date

  • Short dates are written in an “MM/DD/YYYY” format.
  • In some browsers, months or days with no leading zeroes may produce an error.
  • The behavior of “YYYY/MM/DD” is undefined. Some browsers will try to guess the format. Some will return NaN.
  • The behavior of “DD-MM-YYYY” is also undefined. Some browsers will try to guess the format. Some will return NaN.

Long Date

Long dates are most often written in a “MMM DD YYYY” format.
Month and day can be in any order.
A month can be written in full (January), or abbreviated (Jan).
If you write “June 21, 2018” Commas are ignored and Names are case insensitive.

Set Date Methods

  • setDate() Set the day as a number (1-31)
  • setFullYear() Set the year (optionally month and day)
  • setHours() Set the hour (0-23)
  • setMilliseconds() Set the milliseconds (0-999)
  • setMinutes() Set the minutes (0-59)
  • setMonth() Set the month (0-11)
  • setSeconds() Set the seconds (0-59)
  • setTime() Set the time (milliseconds since January 1, 1970)

Get Date Methods

  • getFullYear() Get the year as a four digit number (yyyy)
  • getMonth() Get the month as a number (0-11)
  • getDate() Get the day as a number (1-31)
  • getHours() Get the hour (0-23)
  • getMinutes() Get the minute (0-59)
  • getSeconds() Get the second (0-59)
  • getMilliseconds() Get the millisecond (0-999)
  • getTime() Get the time (milliseconds since January 1, 1970)
  • getDay() Get the weekday as a number (0-6)

Converting Dates to String

If you want to create a string in a standard format, Date provides three methods: –

  • toString( )
  • toUTCString( )
  • toGMTString( )

toUTCString ( ) and toGMTString ( ) format the string according
to Internet (GMT) standards, whereas toString ( ) creates the
string according to Local Time.

Date Methods

  • getDate() Returns the day of the month (from 1-31)
  • getDay() Returns the day of the week (from 0-6)
  • getFullYear() Returns the year
  • getHours() Returns the hour (from 0-23)
  • getMilliseconds() Returns the milliseconds (from 0-999)
  • getMinutes() Returns the minutes (from 0-59)
  • getMonth() Returns the month (from 0-11)
  • getSeconds() Returns the seconds (from 0-59)
  • getTime() Returns the number of milliseconds since midnight Jan 1 1970, and a specified date
  • getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
  • getUTCDate() Returns the day of the month, according to universal time (from 1-31)
  • getUTCDay() Returns the day of the week, according to universal time (from 0-6)
  • getUTCFullYear() Returns the year, according to universal time
  • getUTCHours() Returns the hour, according to universal time (from 0-23)
  • getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
  • getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
  • getUTCMonth() Returns the month, according to universal time (from 0-11)
  • getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
  • now() Returns the number of milliseconds since midnight Jan 1, 1970
  • parse() Parses a date string and returns the number of milliseconds since January 1, 1970
  • setDate() Sets the day of the month of a date object
  • setFullYear() Sets the year of a date object
  • setHours() Sets the hour of a date object
  • setMilliseconds() Sets the milliseconds of a date object
  • setMinutes() Set the minutes of a date object
  • setMonth() Sets the month of a date object
  • setSeconds() Sets the seconds of a date objec
  • setTime() Sets a date to a specified number of milliseconds after/before January 1, 1970
  • setUTCDate() Sets the day of the month of a date object, according to universal time
  • setUTCFullYear() Sets the year of a date object, according to universal time
  • setUTCHours() Sets the hour of a date object, according to universal time
  • setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time
  • setUTCMinutes() Set the minutes of a date object, according to universal time
  • setUTCMonth() Sets the month of a date object, according to universal time
  • setUTCSeconds() Set the seconds of a date object, according to universal time
  • toDateString() Converts the date portion of a Date object into a readable string
  • toISOString() Returns the date as a string, using the ISO standard
  • toJSON() Returns the date as a string, formatted as a JSON date
  • toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions
  • toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions
  • toLocaleString() Converts a Date object to a string, using locale conventions
  • toString() Converts a Date object to a string
  • toTimeString() Converts the time portion of a Date object to a string
  • toUTCString() Converts a Date object to a string, according to universal time
  • UTC() Returns the number of milliseconds in a date since midnight of January 1, 1970,
    • according to UTC time
  • valueOf() Returns the primitive value of a Date object
Tagged : / / /

Top 20 feature in Visual Studio Code in 2021

1.Develop:

Navigate, write, and fix your code fast.

2.Debug:

Debug, profile, and diagnose with ease.

3.Collaborate:

Use version control, be agile, collaborate efficiently.

4.Test:

Write high-quality code with comprehensive testing tools.

5.Extend:

Choose from thousands of extensions to customize your IDE.

6.Code editor:

Visual Studio (like any other IDE) includes a code editor that supports syntax highlighting and code completion using IntelliSense for variables, functions, methods, loops, and LINQ queries.

7.Debugger:

Visual Studio includes a debugger that works both as a source-level debugger and as a machine-level debugger. It works with both managed code as well as native code and can be used for debugging applications written in any language supported by Visual Studio.

8.Designer:

Visual Studio includes a host of visual designers to aid in the development of applications.

Those tools include:-Windows form Designer, WPF Designer, Web designer/development, Class designer, Data designer, Mapping designer.

9.Extensibility:

Visual Studio allows developers to write extensions for Visual Studio to extend its capabilities. These extensions “plug into” Visual Studio and extend its functionality.

10.Products Supported:

It supports multiple products like Microsoft Visual C++, Microsoft Visual C#, Microsoft Visual Basic.

11.Enterprise:

In addition to the features provided by the Professional edition, the Enterprise edition provides a new set of software development, database development, collaboration, metrics, architecture, testing, and reporting tools.

12.Multi-Cursor Shortcuts:

The ability to edit with multiple cursors can be a huge time saver.

13.Text Wrap:

Inside settings.json, simply paste in the following code, and your text will wrap by default.

14.Execute and Debug JavaScript:

There are several great options for executing and debugging JavaScript within Visual Code studio.

like:-Quokka.js, Debugger for Chrome, Code Runner.

15.The Integrated CLI (Command Line Interface):

To save switching between windows, VS Code offers an integrated terminal or CLI. Simply, press CNTRL + ' or CMD + ' to open it up, and the same command to close it. It will automatically open in the directory you have open in VS Code, which saves the navigation step required for operations in a standard terminal.

This makes it easy to install NPM or Yarn dependencies, commit files to Git, and push files to Github — as well as anything else you might want to do via the command line.

16.Prettier:

Prettier is an opinionated code-formatter. It prescribes a certain formatting style as the correct one, but its popularity is making its rules something of an established standard for JavaScript, CSS, and increasing numbers of other languages.

The extension we want is “Prettier — Code formatter” by Esben Peterson. To enable the ESLint integration, add the following code to

 settings.json :

{ "prettier.eslintIntegration": true }

17.ESLint:

ESLint is a powerful and popular linting tool, which helps you spot errors in your code and fix them as you write and which helps you follow common best practices. It’s also a great learning tool.

18.Built-in support for Jupyter notebooks:

Open .ipynb files directly in VS Code.

19.Live Preview extension:

Live HTML preview within VS Code with JavaScript debugging support.

20.Child process tracking and close warnings:

The existing terminal.integrated.confirmOnExit and new terminal.integrated.confirmOnKill settings use child process tracking to display a warning when trying to close a terminal that has child processes under the shell process. By default, this tracking only affects terminals in the editor area but can now be configured to show warnings for all terminals or those in the panel area.

Tagged : / / / /

HTML: Source Tag

The <source> tag is used to embed two or more audio or video files of different media types. The browser may choose the type of file to play based on its media type or codec support.

<audio>
	<source>
	<source>
</audio>
Tagged : / / / / /

HTML: Video tag

The <video>…. </video> tag is used to play video files.

Supports: MP4, Ogg, WebM, etc.

AttributeValueDescription
autoplayautoplayPlay a video file immediately or automatically on the loading of  a web page
controlscontrolsDisplay the controls on a web page such as a play button etc
heightpixelsSets the height of the video player
looploopSpecifies that the video will start over again, every time it is finished
mutedmutedSpecifies that the audio output of the video should be muted
posterURLSpecifies an image to be shown while the video is downloading, or until the user hits the play button
preloadauto
metadata
none
Specifies if and how the author thinks the video should be loaded when the page loads
srcURLSpecifies the URL of the video file
widthpixelsSets the width of the video player
Tagged : / / / /

HTML: Comment

  • Simple Text Comment
<! - - HY! my name is html - - >
  • Code inside comment
<!- -
	<a href="https://www.google.com">Google</a>
	<p>
	Google is very important for us <br> 
	</a>
	- - >
  • Conditional Comment
<!--[if a>=b ]>   	
Text or Code Here
<![endif]-->

Tagged : / / / / / /