Modifying Text Nodes in JavaScript

Properties

  • Data
  • Length

Methods

  • appendData(String)
  • deleteData(start, length)
  • insertData(start, string)
  • replaceData(start, length, string)
  • splitText(start)
  • substringData(start, length)

Length

Length property is used to access the length of Text which indicates the number of characters it contains.

Syntax:- TextNode.length

Data

Data property is used to set or return the value of a text node and comment node objects.

Syntax: –
Sets
TextNode.data = value
Returns
TextNode.data

Ex:- TextNode.data = “Hello DevOpsSchool”;

appendData(String)

This method is used to append the passed string to the end of the text node and comment node.

Syntax: –
TextNode.appendData(String);

Ex: –
TextNode.appendData(“Hello DevOpsSchool”);

deleteData(start, length)

This method is used to delete or remove text content from a text node and comment node. It deletes the specified length of characters starting from index defined in start.

Syntax:-
TextNode.deleteData(start, length);

Ex: –
TextNode.deleteData(0, 5);

insertData(start, string)

This method is used to insert text content to text node and comment node. It inserts the value in string, starting at the character index specified in start.

Syntax:-
TextNode.insertData(start, string)

Ex: –
TextNode.insertData(3, “Hello”)

replaceData(start, length, string)

This method is used to replace text content of text node and comment node. It inserts the value in string, starting at the character index specified in start.

Syntax:-
TextNode.replaceData(start, length, string)

Ex: –
TextNode.replaceData(0, 4, “Hello”)

splitText(start)

The splitText(start) method breaks the Text node into two nodes at the specified start index, keeping both nodes in the tree as siblings. It returns right side of the split in a new text node and leaves the left side in the original.

Syntax: –
var rightSide = TextNode.splitText(start)

Ex: –
var rightSide = TextNode.splitText(5)

substringData(start, length)

It returns the part of the current element’s (TextNode and CommentNode) text content from the specified position with the specified length.

Syntax:-
TextNode.substringData(start, length)

Ex: –
TextNode.substringData(2, 5);

Tagged : / /

Difference between innerHTML and outerHTML in JavaScript

innerHTML

The Element property innerHTML gets or sets the HTML or XML markup contained within the element.
Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
It is recommended you should not use innerHTML when inserting plain text; instead, use textContent.

outerHTML

The outerHTML is the HTML of an element including the element itself. Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.

What is the difference between innerText and outerText?

The innerText property works similarly to the innerHTML property, except that it is focused solely on the textual content contained within an element. The innerText property sets or returns the text content of the specified node, and all its descendants. If you set the innerText property, any child nodes are removed and replaced by a single Text node containing the specified string. This feature was originally introduced by Internet Explorer and was formally specified in the HTML standard in 2016 after being adopted by all major browser vendors. To set or return the HTML content of an element, use the innerHTML property.

outerText

outerText property works similarly to the outerHTML property, modifies the element itself, and replaces it with a single text node. This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user.

Tagged : / / / / / /

Insert( ) Method in JavaScript

The insertBefore() method is used to insert a node before the reference node as a child of a specified parent node. If the given child is a reference to an existing node in the document, insertBefore( ) moves it from its current position to the new position.

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

Syntax: –

parentNode.insertBefore(newNode, referenceNode);

insertAdjacentElement ( ) Method

The insertAdjacentElement() method inserts the specified element into a given specified position. It returns the element that was inserted, or null if the insertion failed.

Syntax:-

element – The element to be inserted into the tree.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

insertAdjacentHTML ( ) Method

The insertAdjacentHTML() method is used to insert a text as HTML (parses the specified text as HTML or XML) into a specified position.

Syntax:-

text – The string to be parsed as HTML or XML and inserted into the tree.
It is recommended you not use insertAdjacentHTML when inserting plain text instead, use the node.textContent property

insertAdjacentText ( ) Method

The insertAdjacentText() method inserts the specified element into a specified position.

Syntax:-

text – The text which is about to insert.
The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

Tagged : / / / /

How is Node.js created with JavaScript?

Creating Nodes

  • createElement(element_name)
  • createTextNode(string)
  • createComment(string)
  • createDocumentFragment( )

Create Element Node

The createElement(element_name) method is used to create the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized. It returns the New Element.

Syntax:-
createElement(element_name)

Create Text Node

The createTextNode(string) method is used to create the Text Node with the specified text (string).

Syntax:-
createTextNode(string)

Create Comment Node

The createComment(string) method is used to create the Comment Node with the specified string and returns it.

Syntax:-
createComment (string)

Document Fragment

  • The DocumentFragment interface represents a minimal document object that has no parent.
  • A common use for Document Fragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild( ) or insertBefore( ).
  • Document fragment isn’t part of the active document tree structure, changes made to the fragment don’t affect the document.
  • Doing this moves the fragment’s nodes into the DOM, leaving behind an empty Document Fragment.
  • An empty Document Fragment can be created using the document.createDocumentFragment() method.

Create Document Fragment

The createDocumentFragment() method creates a imaginary Node object, with all the properties and methods of the Node object.

Tagged : / / / /

How To Traverse The DOM In JavaScript?

DOM Traversal

  • parentNode – Returns parent node
  • parentElement – Returns parent element node
  • childNodes – Returns collection of an element’s child nodes (including text and comment nodes)
  • children – Returns a collection of an element’s child element node (do not include text and comment nodes)
  • firstChild – Returns first child node of an element (it can be text or comment node)
  • firstElementChild – Returns first child element node of an element
  • lastChild – Returns last child node of an element (it can be text or comment node)
  • lastElementChild – Returns last child element node of an element
  • previousSibling – Returns previous node of the same level (it can be text or comment node)
  • previousElementSibling – Returns previous element node of the same level
  • nextSibling – Returns next node of same level (it can be text or comment node)
  • nextElementSibling – Returns next element of same level

parentNode and parentElement

The parentNode read-only property returns the parent of the specified node in the DOM tree.

The parentElement property returns the parent element of the specified element. If the parent node is not an element node, it returns null.

childNodes

The childNodes read-only property returns a live NodeList of child nodes of the given element where the first child node is assigned index 0. childNodes includes all child nodes, including non-element nodes like text and comment nodes.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.
  • You can use the length property of the NodeList object to determine the number of child nodes, then you can loop through all child nodes and extract the other info.

children

The children property returns collection of child elements of the given element where the first child is assigned index 0. children include only element nodes (no whitespace, text node, and comment node).

  • You can use the length property of the NodeList object to determine the number of child nodes, then you can loop through all child nodes and extract the other info.

firstChild

The firstChild property returns the node’s first child in the tree, or null if the node has no children. If the node is a Document, it returns the first node in the list of its direct children. It includes a text node and a comment node.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.

firstElementChild

The firstElementChild property returns the element’s first child element node in the tree, or null if the node has no children element. It ignores text node and comment node or any whitespaces.

lastChild

The lastChild read-only property returns the last child of the node. If its parent is an element, then the child is generally an element node, a text node, or a comment node. It returns null if there are no child elements.

  • Whitespace inside elements is considered as text, and text is considered as nodes.
  • Any whitespace will create a #text node, from a single space to multiple spaces, returns, tabs, and so on.

lastElementChild

The lastElementChild property returns the element’s last child element node in the tree, or null if the node has no children element. It ignores text node and comment node or any whitespaces.

previousSibling

The previousSibling read-only property returns the node immediately preceding the specified one in its parent’s childNodes list, or null if the specified node is the first in that list. It includes text node and comment node or any whitespace.

previousElementSibling

The previousElementSibling property returns the element node immediately preceding the specified one in its parent’s node list, or null if the specified node is the first in that list. It ignores the text node and comment node or any whitespace.

nextSibling

The nextSibling read-only property returns the node immediately following the specified one in its parent’s childNodes list, or null if the specified node is the last node in that list. It includes text node and comment node or any whitespace.

nextElementSibling

The nextElementSibling read-only property returns the element node immediately following the specified one in its parent’s node list, or null if the specified node is the last node in that list. It ignores the text node and comment node or any whitespace.

ownerDocument

The ownerDocument read-only property returns the top-level document object for this node. In HTML, the HTML document itself is always the ownerDocument of an element.

Tagged : / / /

How to Use CSS Selector in javascript?

querySelector(“CSS Selector”)

The method querySelector() returns the first Element match of the specified selector or group of selectors. If no matches are found, null is returned.

querySelectorAll(“CSS Selector”)

The method querySelectorAll() returns a static (not live) NodeList representing a list of the document’s elements that match the specified group of selectors.

  • The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
  • You can use the length property of the NodeList object to determine the number of elements that matches the specified selector, then you can loop through all elements and extract the info you want.
  • If the specified selectors include a CSS pseudo-element, the returned list is always empty.

querySelectorAll(“CSS Selector”)

querySelectorAll(“CSS Selector”)

More specific

querySelectorAll(“CSS Selector”)

  • Length Property
  • Loop

innerHTML

The innerHTML property defines the HTML content.

Tagged : / / /

What is the Purpose of the Node Object Property in JavaScript

Properties of Node Object

The Node object represents a single node in the document tree.

  • nodeName
  • nodeValue
  • nodeType
  • textContent
  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • previousSibling
  • nextSibling

nodeName

The nodeName read-only property returns the name of the current node as a string.

  • CDATASection “#cdata-section”
  • Comment “#comment”
  • Document “#document”
  • DocumentFragment “#document-fragment”
  • DocumentType The value of DocumentType.name
  • Element The value of Element.tagName
  • Entity The entity name
  • EntityReference The name of entity reference
  • Notation The notation name
  • ProcessingInstruction The value of ProcessingInstruction.target
  • Text “#text”

nodeValue

The nodeValue property returns or sets the value of the current node.

  • CDATASection content of the CDATA Section
  • Comment content of the comment
  • Document null
  • DocumentFragment null
  • DocumentType null
  • Element null
  • NamedNodeMap null
  • EntityReference null
  • Notation null
  • ProcessingInstruction entire content excluding the target
  • Text content of the text node

nodeType

The read-only Node.nodeType property represents the type of the node.

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.

Tagged : / / / / /

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 : / / /

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 : / / /