0% found this document useful (0 votes)
14 views29 pages

Understanding the Document Object Model

The document explains the Document Object Model (DOM) and how JavaScript interacts with HTML elements, allowing for dynamic changes to the web page. It details various collections such as anchors, links, and images, along with their properties and methods for accessing and modifying these elements. Additionally, it covers the creation of Date objects and basic string handling in JavaScript.

Uploaded by

suryasahoo396
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views29 pages

Understanding the Document Object Model

The document explains the Document Object Model (DOM) and how JavaScript interacts with HTML elements, allowing for dynamic changes to the web page. It details various collections such as anchors, links, and images, along with their properties and methods for accessing and modifying these elements. Additionally, it covers the creation of Date objects and basic string handling in JavaScript.

Uploaded by

suryasahoo396
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Document and its associated objects

Document is just the web page.


Objects are elements.
For ex:<head></head> is an object.
<body></body> is an object.
<p></p> is an object.

The way document content is accessed and modified is called


the Document Object Model, or DOM.
Use the DOM when interact with web page.

With the object model, JavaScript gets all the power it needs
to create dynamic HTML:

• JavaScript can change all the HTML attributes in the page


• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements andattributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

The following properties and methods can be used on HTML documents:

• anchor
• Link
• Area
• Image
• Applet
• Layer

• anchor
The anchors collection returns a collection of all <a>
elements in the document that have a name attribute.
Ex:
Output:

After clicking on button

Syntax
[Link]

Properties
Property Description

Length Returns the number of <a> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <a> element from the collection with the specified index
(starts at 0).
Note: Returns null if the index number is out of range

item(index) Returns the <a> element from the collection with the specified index
(starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <a> element from the collection with the specified id.

Note: Returns null if the id does not exist

Example
Get the HTML content of the first <a> element in the document:

var x = [Link][0].innerHTML;

The result of x will be:

HTML Tutorial

<html>
<body>

<a name="html">HTML Tutorial</a><br>


<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>

<p>Click the button to display the HTML content of the first anchor in the
document.</p>

<input type=”button” value=”show” onclick="myFunction()">Try it


<p id="demo"></p>

<script>
function myFunction() {
var x = [Link][0].innerHTML;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
• Link

The links collection returns a collection of all links in the document.


The links in the collection represents <a> elements and/or
<area> elements with a href attribute.

If the element is missing the href attribute, nothing is returned.

Ex:

Output:

After clicking on button

Syntax
[Link]
Properties
Property Description

Length Returns the number of <a> and/or <area> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <a> and/or <area> element from the collection with the
specified index (starts at 0).

Note: Returns null if the index number is out of range

item(index) Returns the <a> and/or <area> element from the collection with the
specified index (starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <a> and/or <area> element from the collection with the
specified id.

Note: Returns null if the id does not exist

More Examples
<html>
<body>

<imgsrc ="[Link]" width="145" height="126" alt="Planets" usemap ="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="[Link]" alt="Sun">
<area shape="circle" coords="90,58,3" href="[Link]" alt="Mercury">
<area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
</map>

<p>
<a href="/html/[Link]">HTML</a><br>
<a href="/css/[Link]">CSS</a>
</p>

<p>Click the button to display the URL of the first link (index 0) in the document.</p>

<input type=”button” onclick="myFunction()">Try it

<p id="demo"></p>
<script>
function myFunction() {
var x = [Link][0].href;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>

Get the URL of the first link (index 0) in the document:

var x = [Link](0).href;

The result of x will be:

[Link]

<html>
<body>

<imgsrc ="[Link]" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="[Link]" alt="Sun">
<area shape="circle" coords="90,58,3" href="[Link]"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
</map>

<p>
<a href="/html/[Link]">HTML</a><br>
<a href="/css/[Link]">CSS</a>
</p>

<p>Click the button to display the URL of the first link (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link](0).href;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
namedItem(id)

Get the URL of the element with id="myLink" in the document:

var x = [Link]("myLink").href;

The result of x will be:

[Link]

<html>
<body>

<imgsrc ="[Link]" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="[Link]" alt="Sun">
<area shape="circle" coords="90,58,3" href="[Link]"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
</map>

<p>
<a id="myLink" href="/html/[Link]">HTML</a><br>
<a href="/css/[Link]">CSS</a>
</p>

<p>Click the button to display the URL of the element with


id="myLink".</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]("myLink").href;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
Add a red border to the first link in the document:

[Link][0].[Link] = "5px solid red";


<html>
<body>

<p>
<a href="/html/[Link]">HTML</a><br>
<a href="/css/[Link]">CSS</a>
</p>

<p>Click the button to add a red border to the first link in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
[Link][0].[Link] = "5px solid red";
}
</script>

</body>
</html>
Example
Loop through all links in the document, and output the URL (href) of each link:

var x = [Link];
var txt = "";
var i;
for (i = 0; i<[Link]; i++) {
txt = txt + x[i].href + "<br>";
}
The result of txt will be:https

[Link]
[Link]
[Link]
[Link]
[Link]

<html>
<body>

<imgsrc ="[Link]" width="145" height="126" alt="Planets" usemap


="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="[Link]" alt="Sun">
<area shape="circle" coords="90,58,3" href="[Link]"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="[Link]" alt="Venus">
</map>

<p>
<a href="/html/[Link]">HTML</a><br>
<a href="/css/[Link]">CSS</a>
</p>

<p>Click the button to display the URL of each link in the document.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link];
var txt = "";
var i;
for (i = 0; i<[Link]; i++) {
txt = txt + x[i].href + "<br>";
}
[Link]("demo").innerHTML = txt;
}
</script>

</body>
</html>
• Image
The images collection returns a collection of all
<img> elements in the document.
Ex:

Ouput:

After clicking on button

Syntax
[Link]

Properties
Property Description
Length Returns the number of <img> elements in the collection.

Note: This property is read-only

Methods
Method Description

[index] Returns the <img> element from the collection with the specified
index (starts at 0).

Note: Returns null if the index number is out of range

item(index) Returns the <img> element from the collection with the specified
index (starts at 0).

Note: Returns null if the index number is out of range

namedItem(id) Returns the <img> element from the collection with the specified id.

Note: Returns null if the id does not exist

Example
[index]

Get the URL of the first <img> element (index 0) in the document:

var x = [Link][0].src;

The result of x will be:


[Link]

<html>
<body>

<img src="[Link]" alt="flower" width="150" height="113">


<img src="[Link]" alt="flower" width="152" height="128">
<img src="[Link]" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of the first image (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
<script>
function myFunction() {
var x = [Link][0].src;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
item(index)

Get the URL of the first <img> element (index 0) in the document:

var x = [Link](0).src;

The result of x will be:

[Link]

<html>
<body>

<imgsrc="[Link]" alt="flower" width="150" height="113">


<imgsrc="[Link]" alt="flower" width="152" height="128">
<imgsrc="[Link]" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of the first image (index 0) in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link](0).src;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
namedItem(id)

Get the URL of the <img> element with id="myImg" in the document:

var x = [Link]("myImg").src;

The result of x will be:

[Link]

<html>
<body>

<img src="[Link]" alt="flower" width="150" height="113">


<img src="[Link]" alt="flower" width="152" height="128">
<img id="myImg" src="[Link]" alt="Smiley face" width="42"
height="42">

<p>Click the button to display the URL of the img element with
id="myImg".</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]("myImg").src;
[Link]("demo").innerHTML = x;
}
</script>

</body>
</html>
Example
Add a black dotted border to the first <img> element in the document:

[Link][0].[Link] = "10px dotted black";


<html>
<body>

<imgsrc="[Link]" alt="flower" width="150" height="113">


<imgsrc="[Link]" alt="flower" width="152" height="128">
<img id="myImg" src="[Link]" alt="Smiley face" width="42"
height="42">
<p>Click the button to add a black dotted border of the first image in the
document.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link][0];
[Link] = "10px dotted black";
}
</script>

</body>
</html>
Example
Loop through all <img> elements in the document, and output the URL (src) of each image:

var x = [Link];
var txt = "";
var i;
for (i = 0; i<[Link]; i++) {
txt = txt + x[i].src + "<br>";
}

The result of txt will be:

[Link]
[Link]
[Link]
<html>
<body>

<img src="[Link]" alt="flower" width="150" height="113">


<img src="[Link]" alt="flower" width="152" height="128">
<img src="[Link]" alt="Smiley face" width="42" height="42">

<p>Click the button to display the URL of each img element in the
document.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p id="demo"></p>
<script>
function myFunction() {
var x = [Link];
var txt = "";
var i;
for (i = 0; i<[Link]; i++) {
txt = txt + x[i].src + "<br>";
}
[Link]("demo").innerHTML = txt;
}
</script>

</body>
</html>

• area
The Area object represents an

HTML <area> element. Ex:

Output:
After clicking on button

[Link]
Applets are Internet programs, designed to communicate
across the Net and execute within a web browser.

applet tag is not supported in html5.

Layer
Layers are objects on the map that consist of one or more
separate items, but are manipulated as a single unit. Layers
generally reflect collections of objects that you add on top of
the map to designate a common association.

Creating Date Objects


Date objects are created with the new Date() constructor.

There are 4 ways to create a new date object:

new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(date string)

new Date()
new Date() creates a new date object with the current date and time:

Example
const d = new Date();

new Date(dateString)
new Date(dateString) creates a new date object from a date string:

Example
const d = new Date("October 13, 2014 11:13:00");

These methods can be used for getting information from a date object:

Method Description

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)

getDay() Get the weekday as a number (0-6)

JavaScript Strings
A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

var carName1 = "Volvo XC60";


var carName2 = 'Volvo XC60';

String indexes are zero-based: The first character is in position 0, the second
in 1, and so on.
String Properties
Property Description

Length Returns the length of a string

var str = "Hello World!";


[Link] // Returns 12

String Methods
All string methods return a new value. They do not change the original
variable.
Method Description

charAt() Returns the character at the specified index (position)

var str = "HELLO WORLD";


[Link](0) // Returns "H"

concat() Joins two or more strings, and returns a new joined strings

var str1 = "Hello ";


var str2 = "world!";
var res = [Link](str2);

endsWith() Checks whether a string ends with specified string/characters

var str = "Hello world";


[Link]("world") // Returns true
[Link]("World") // Returns false

fromCharCode() Converts Unicode values to characters

[Link](65) // Returns "A"

includes() Checks whether a string contains the specified string/characters

var str = "Hello world, welcome to the universe.";


[Link]("world") // Returns true

indexOf() Returns the position of the first found occurrence of a specified value in a
string

let str = "Hello world, welcome to the universe.";


[Link]("welcome") // Returns 13
[Link]("Welcome") // Returns -1

lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string

var str = "Hello planet earth, you are a great planet.";


[Link]("planet") // Returns 36
[Link]("Planet") // Returns -1

match() The [Link]() is an inbuilt function in JavaScript used to search a


string for a match against any regular expression. If the match is found, then
this will return the match as an array.
syntax

[Link](regExp)

<script>

var str = "Welcome to peeks for peeks!";

[Link]([Link](/eek/g));

</script>
Output:
eek, eek
In the above example, substring “eek” will match with the given string, and
when a match is found, it will return an array of string objects. Here “g” flag
indicates that the regular expression should be tested against all possible
matches in a string.
[Link]([Link](/eek/i);

Here “i” parameter helps to find the case-insensitive match in


the given string.

repeat() Returns a new string with a specified number of copies of an existing string

<script>

var str = "Hello world!";

[Link]([Link](2));

</script>

replace() Searches a string for a specified value, or a regular expression, and returns
a new string where the specified values are replaced

<script>
var str = "Visit Microsoft!";

[Link]([Link]("Microsoft", "Infosys"));

</script>

search() Searches a string for a specified value, or regular expression, and returns
the position of the match

var str = "Visit W3Schools!";


[Link]("W3Schools") // Returns 6

slice() Extracts a part of a string and returns a new string

var str = "Hello world!";


[Link](0, 5) // Returns "Hello"

split() Splits a string into an array of substrings

var str = "How,are,you doing today?";


const myArr = [Link](",");

[Link](myArr[3]);//doing

startsWith() Checks whether a string begins with specified characters

var str = "Hello world, welcome to the universe.";


[Link]("Hello") // Returns true

substr() Extracts the characters from a string, beginning at a specified start position,
and through the specified number of character

var str = "Hello world!";


[Link](1, 4) // Returns "ello"

substring() Extracts the characters from a string, between two specified indices

var str = "Hello world!";


[Link](1, 4) // Returns "ell"

toLowerCase() Converts a string to lowercase letters

var str = "Hello World!";


[Link]();

toUpperCase() Converts a string to uppercase letters

var str = "Hello World!";


[Link]() // Returns "HELLO WORLD!"

trim() Removes whitespace from both ends of a string

var str = " Hello World! ";


[Link]() // Returns "Hello World!"

JavaScript Number Methods


Let's see the list of JavaScript number methods with their description.

Methods Description

isInteger() It determines whether the given value is an integer.

Example 1
Let's see a simple example of isInteger() method.

<script>
var x=0;
var y=1;
var z=-1;
[Link]([Link](x));
[Link]([Link](y));
[Link]([Link](z));
</script>
Output:

true true true

Example 2
isInteger() method with some test cases.

1. <script>
2. function check(x,y)
3. {
4. return x/y;
5. }
6. [Link]([Link](check(12,2)));
7. [Link]([Link](check(12,5)));
8. </script>

Output:

true false

parseFloat() It converts the given string into a floating point number.


script>
var a="50";
var b="50.25"
var c="String";
var d="50String";
var e="50.25String"
[Link]([Link](a)+"<br>");
[Link]([Link](b)+"<br>");
[Link]([Link](c)+"<br>");
[Link]([Link](d)+"<br>");
[Link]([Link](e));
</script>

Output:

50
50.25
NaN
50
50.25
parseInt() It converts the given string into an integer number.
1. <script>
2. var a="50";
3. var b="50.25"
4. var c="String";
5. var d="50String";
6. var e="50.25String"
7. [Link]([Link](a)+"<br>");
8. [Link]([Link](b)+"<br>");
9. [Link]([Link](c)+"<br>");
10. [Link]([Link](d)+"<br>");
11. [Link]([Link](e));
12. </script>

Output:

50
50
NaN
50
50

toString() It returns the given number in the form of string.


1. <script>
2. var a=50;
3. var b=-50;
4. var c=50.25;
5. [Link]([Link]()+"<br>");
6. [Link]([Link]()+"<br>");
7. [Link]([Link]());
8. </script>

Output:

50
-50
50.25
JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.

The default value of JavaScript Boolean object is false.

1. Boolean b=new Boolean(value);

let x = false;

But booleans can also be defined as objects with the keyword new:

let y = new Boolean(false);

Example
let x = false;
let y = new Boolean(false);

// typeof x returns boolean


// typeof y returns object

JavaScript Math

Method Description

abs(x) Returns the absolute value of x

[Link](-4.7); // returns 4.7

ceil(x) Returns x, rounded upwards to the nearest integer

[Link](4.9); // returns 5
[Link](4.7); // returns 5
[Link](4.4); // returns 5
[Link](4.2); // returns 5
[Link](-4.2); // returns -4

floor(x) Returns x, rounded downwards to the nearest integer

[Link](4.9); // returns 4
[Link](4.7); // returns 4
[Link](4.4); // returns 4
[Link](4.2); // returns 4
[Link](-4.2); // returns -5

max(x, y, z, ..., n) Returns the number with the highest value

[Link](0, 150, 30, 20, -8, -200); // returns 150

min(x, y, z, ..., n) Returns the number with the lowest value

[Link](0, 150, 30, 20, -8, -200); // returns -200

pow(x, y) Returns the value of x to the power of y

[Link](8, 2); // returns 64

round(x) Rounds x to the nearest integer

[Link](4.9); // returns 5
[Link](4.7); // returns 5
[Link](4.4); // returns 4
[Link](4.2); // returns 4
[Link](-4.2); // returns -4

sign(x) Returns the sign of a number (checks whether it is positive, negative

[Link](-4); // returns -1
[Link](0); // returns 0
[Link](4); // returns 1

sqrt(x) Returns the square root of x

[Link](64); // returns 8

trunc(x) Returns the integer part of a number (x)

[Link](4.9); // returns 4
[Link](4.7); // returns 4

What is an Array?
In JavaScript, array is a single variable that is used to store different elements. It is
often used when we want to store list of elements and access them by a single
variable.
Declaration of an Array
There are basically two ways to declare an array.
Example:

var House = [ ]; // method 1


var House = new Array(); // method 2

Initialization of an Array
Example (for Method 1):

// Initializing while declaring


Var house = ["1BHK", "2BHK", "3BHK", "4BHK"];

Example (for Method 2):


// Initializing while declaring

// Creates an array having elements 10, 20, 30, 40, 50

Var house = newArray(10, 20, 30, 40, 50);

//Creates an array of 4 undefined elements

Var house1 = newArray(4);

// Now assign values

house1[0] = "1BHK"

house1[1] = "2BHK"

house1[2] = "3BHK"

house1[3] = "4BHK

//Creates an array with element 1BHK

varhome = newArray("!BHK");

An array in JavaScript can hold different elements


We can store Numbers, Strings and Boolean in a single array.
Example:
// Storing number, boolean, strings in an Array
Var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];

Accessing Array Elements


Array in JavaScript are indexed from 0 so we can access array
elements as follows:
var house = ["1BHK", 25000, "2BHK", 50000, "Rent", true];
alert(house[0]+" cost= "+house[1]);
var cost_1BHK = house[1];
var is_for_rent = house[5];
alert("Cost of 1BHK = "+ cost_1BHK);
alert("Is house for rent = ")+ is_for_rent);

Adding / removing elements

 push() – add one or more elements to the end of an array.

let fruits = ["Banana", "Orange", "Apple", "Mango"];


[Link]("Kiwi");


 unshift() – add one or more elements to the beginning of an array.
 let fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Lemon");

 pop() – remove an element from the end of an array.
 Let fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
 shift() – remove the first element from an array.
 let fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
 splice() – manipulate elements in an array such as deleting, inserting, and
replacing elements.

[Link] (start, deleteCount, item 1, item 2….)


Parameters:
Start : Location at which to perform operation
deleteCount: Number of element to be deleted,
if no element is to be deleted pass 0.
Item1, item2 …..- this is an optional parameter .
These are the elements to be inserted from location start

// Removing an adding element at a particular location


// in an array
// Declaring and initializing arrays
var number_arr = [ 20, 30, 40, 50, 60];
var string_arr = [ "amit", "sumit", "anil", "prateek"];
// splice()
// deletes 3 elements starting from 1
// number array contains [20, 60]
number_arr.splice(1, 3);
// doesn't delete but inserts 3, 4, 5
// at starting location 1
number_arr.splice(1, 0, 3, 4, 5);

// deletes two elements starting from index 1


// and add three elements.
// It contains ["amit", "xyz", "geek 1", "geek 2", "prateek"];
string_arr.splice(1, 2, "xyz", "geek 1", "geek 2");

// Printing both the array after performing splice operation


[Link]("After splice op "+ number_arr);
[Link]("After splice op "+ string_arr);

Common questions

Powered by AI

The links collection can be utilized to access all <a> and <area> elements in a document that have an href attribute. You can determine the number of links using the length property, access specific links using an index or by namedItem. Methods like item(index) allow retrieving elements from the collection, but they return null if the index is out of range or if the id doesn't exist . A limitation is that the collection includes only those elements with an href attribute, so any elements without it are ignored. This collection is read-only, so while you can manipulate node properties, you cannot directly change the collection itself .

The push() and pop() methods are used to manipulate arrays in JavaScript. push() adds one or more elements to the end of an array, effectively expanding its length, while pop() removes the last element, reducing the array's length. For example, if you have an array of fruits, fruits.push("Kiwi") adds "Kiwi" to the end, making it the last element of the array. Conversely, fruits.pop() removes the last element, "Mango" as in this array: ["Banana", "Orange", "Apple", "Mango"] becomes ["Banana", "Orange", "Apple"] after pop. These methods are useful for managing stack-like structures, recording operations, or dynamically adjusting data .

Images in a document can be accessed and manipulated using the images collection in JavaScript, which provides properties and methods to interact with <img> elements. The length property returns the number of images, while methods like item(index) or the [index] method fetch <img> elements by index. Similarly, namedItem(id) retrieves an image by its id. These methods allow retrieval of attributes like the image source (src), and style modifications can also be applied, such as adding a border to an image . For example, the URL of an image can be accessed with document.images[0].src, returning the source of the first image . Additionally, images can be manipulated by looping through them using for-loops .

The concat() method in JavaScript joins two or more strings, returning a new combined string without altering the original strings. For example, 'Hello '.concat('World!') results in 'Hello World!'. This method is straightforward for merging strings when building dynamic content or processing user inputs. Its utility lies in its simplicity and the ability to manage string concatenation cleanly without operant overload or side effects on the original variables. It is especially useful in constructing messages, URLs, or any situation requiring dynamic string composition .

JavaScript can manipulate HTML events by adding dynamic functionality to web pages. It can react to all existing HTML events like clicks, changes, and form submissions, or create new events to handle situations specific to an application. For instance, JavaScript can change the content of an element when a button is clicked by attaching an onclick event that triggers a function to modify that element. This capability is significant in web development as it enhances interactivity, allowing developers to create responsive and engaging websites that react intelligently to user actions .

The string.match() method in JavaScript is used to search a string for a match against a regular expression. If a match is found, it returns an array containing all the matches; otherwise, it returns null. This method is case-sensitive, unless the 'i' flag is used, and can be used with the 'g' flag to find all matches within the string. For example, str.match(/eek/g) will return ['eek', 'eek'] when applied to "Welcome to peeks for peeks!", as it matches the substring 'eek' globally within the string .

JavaScript interacts with web page elements through the Document Object Model (DOM), which allows it to access and modify both the content and structure of a web page dynamically. Through the DOM, JavaScript can change HTML attributes, CSS styles, remove or add HTML elements, and react to or create HTML events. For example, using JavaScript, you can change the HTML content of the first anchor element by accessing it through the anchors collection and modifying its innerHTML property .

The parseFloat and parseInt methods in JavaScript are used to convert strings to numbers, but they serve different purposes. parseFloat() converts a string to a floating-point number and can handle decimal numbers, whereas parseInt() converts to an integer and truncates any decimal part. parseInt() can also handle strings with initial numbers and non-numeric trailing characters, stopping conversion at the first non-numeric character. For example, parseFloat("50.25") returns 50.25, while parseInt("50.25") returns 50. parseFloat is used when the input string represents a floating-point number and precision is needed. parseInt is used when only an integer value is required .

Math.round() rounds a number to the nearest integer, while Math.floor() rounds downwards to the nearest integer and Math.ceil() rounds upwards. Math.round(4.7) yields 5, as does Math.ceil(4.7), but Math.floor(4.7) yields 4. Math.round() is useful when you want to round to the closest integer, considering up if the decimal is 0.5 or higher. Math.floor() is beneficial in scenarios where rounding down is needed, such as allocating resources or creating maximum thresholds without exceeding limits. Math.ceil() is effective for rounding up, such as in scenarios requiring minimum billing or ceiling limits .

The unshift() method adds one or more elements to the beginning of an array, shifting existing elements towards higher indices, while the shift() method removes the first element from an array, shifting subsequent elements towards lower indices. In practical terms, unshift(["Lemon", "Banana", "Orange"]) adds "Lemon" at the array's start, while shift(["Banana", "Orange", "Apple"]) removes "Banana", the first element. unshift is useful when inserting priority elements, maintaining chronologically ordered data, or customizing data structures. shift is effective for queue-like operations and managing time-ordered data .

You might also like