HTML Interview Questions

Are you worried about how you would excel in your next HTML Developer job interview and what exactly you need to crack the same? If yes, then look no further. Our team, formed by formerly experienced interviewers, have created 30 HTML interview questions and answers, with 12 of them being of intermediate-level and 18 of advanced-level to help you succeed in answering all the tricky questions with assurance and confidence.

  • 4.5 Rating
  • 30 Question(s)
  • 15 Mins of Read
  • 7654 Reader(s)

Intermediate

The various tags provided for better structuring in HTML5 are:

<header> - This tag is used to define a header for a document or section

<footer> - This tag defines a footer for a document or section

<section> - It defines a section in a document

<summary> - It provides a visible heading for a <details> element.

<details> - It defines additional details that can be viewed or hidden by the user

<command> - It defines a command button to be invoked by the user

<hgroup> - When there are multiple levels in a heading, it groups a set of <h1> to <h6> elements.

<dialog> - It defines a dialog box.

<figure> - This tag specifies content like illustrations, diagrams, photos, code listings, etc.

<figcaption> - It is used to provide a caption for a <figure> element

<article> - This tag defines an article.

<aside> - It defines content other than the page content.

<bdi> - This tag isolates a part of text for formatting in a different direction from other text.

<mark> - It defines highlighted text.

<meter> - It defines a scalar measurement within a known range.

<nav> - It defines links for navigation.

<progress> - This tag exhibits the progress of a task.

<ruby> - It defines a ruby annotation for East Asian typography.

<rt> - It defines an explanation/pronunciation of characters for East Asian typography.

<rp> - This tag tells the system what to display in browsers that do not support ruby annotations.

<time> - This tag defines a date/time.

<wbr> - This tag defines a line-break.

List of new Media Elements that have been added in HTML5 are :

<audio> - It defines sound content

<video> - It defines a video or a movie

<source> - This tag defines the multiple media resources for <video> and <audio>

<embed> - It provides a container for an external application or interactive content

<track> - It defines text tracks for <video> and <audio>.

No character encoding declared at the document level for below document can be as below.

Original Code

<!DOCTYPE html>
<html>
     <head>
<title>HTML5 Programming</title>
     </head>
     <body>
     <body>
</html>

Corrected Code

This can be fixed by declaring the Character Set. Use UTF-8 Character encoding and add this markup to head section.

<!DOCTYPE html>
<html>
     <head >
           <meta charset ="UTF-8">
<title>HTML5 Programming</title>
     </head>
     <body>
     <body>
</html>

Example

<!DOCTYPE html>
<html>
     <head>
           <meta charset ="UTF-8">
           <title>Block Level Elements</title>
     </head>
     <body>
           <p>I am a paragraph</p>I am directly after the paragraph
     <body>
</html>

Output

Example

<!DOCTYPE html>

<html>
     <head>
           <meta charset ="UTF-8">
           <title>Block Level Elements</title>
     </head>
     <body>
           <h1>Level 1 Heading</h1>
           <h2>Level 2 Heading</h2>
           <div>This is a logical divison<div>
           <hr>
           I will have a horizantal rule above me
           <ol>
<li>I am part of an ordered list</li>
<li>li stands for list item</li>
<li>You can add as many as you want</li>
           </ol>
           <ul>
<li>I am still a list item</li>
<li>This time I am inside an un-ordered list</li>
<li>Notice how I'm rendered in the browser</li>
           </ul>
     <body>
</html>

Output

The Strong and em tags are new semantic inline elements  to specify the relative importance of their content. Search engines use <em> and <strong> to rank content.

<em> was emphasis and is now for stress emphasis, such as something pronounce differently.  The “stress” being referred to is linguistic; if spoken it would be emphasized pronunciation on a word that can change the nuance of a sentence.

For example "Call a doctor now!" stresses doctor, perhaps in reply to someone asking "She looks thirsty, should I call a homoeopath?" In comparison, "Call a doctor now!"  changes the emphasis on doing so quickly.

<strong> was for stronger emphasis and is now for strong importance for its content. Strong indicate relative importance by  nesting <strong> elements

Example 

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Text Modifiers</title>
    </head>
    <body>
          The <strong>strong tag</strong> will render bold text.
          <br>
          The <em>em tag</em> will render italic text.
    <body>
</html>

Output

An image can be inserted into the document using <img>. Use the src attribute to specify the URL containing the image. alt attribute (alternative attribute) is used to provide a brief description of the image. This alternative description should be written specifically for screen readers to read and for displaying when the image fails to download. Decorative images are best displayed as background images, but if we need to use a decorative <img> element, include the alt attribute, but leave it empty.

Because a browser downloads each image separately, it needs to know the image’s height and width so it can create a placeholder for the image while the image downloads. Otherwise, after each image is downloaded and its real size becomes known, a browser has to reflow the page. This slows the rendering and annoys the user. To set an image’s size, we can use the width and height attributes of <img> or the width and height CSS properties.

Example:

<img src="FILE.EXT" width="IMAGE_WIDTH" height="IMAGE_HEIGHT" alt="BRIEF_IMAGE_DESCRIPTION" />

<aside>:  Piece of content that is tangentially related to the content that surrounds it but isn’t essential for understanding that content. <aside> content should be added to the main content; that is, any related content. While print design can provide inspiration, don’t stop at pull quotes.

For example, a footnote provides extra but unessential information, and a pull quote (while essential content) is a quoted copy of the text from the main content. However, keep in mind the <aside> must be related. Having your site’s sidebar in an <aside> as a child of <body> is fine, but site-wide information shouldn’t appear in an <aside> that is the child of an <article>, for example. Also, <aside> would be appropriate for advertising, as long as it was related to the parent sectioning element. Here is an example <aside> providing extra information in the margin of an article.  

Example

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Images</title>
      <style type="text/css">
       h1 { font-size:160%; font-weight:bold; }
       aside, section, article { display:block;  }
       section { width:400px; margin:auto; }
       article { width:405px; text-align:left;  }
       aside { width:200px; padding:5px; margin:5px 5px 5px 5px; float: right; border:1px black solid; }
    </style>
    </head>
    <body>
          <article>
         <h1>Which OS are you using?</h1>
         <section>
             <b>The answer is all of them.</b> If you survey a group of people you will
                     get very different answers…IWindows 10.
                  <aside>Majority of the people use Windows 10. </aside> macOS, Linux and mobile operating systems are available
         </section>
          </article>
    <body>
</html>

Output

This <mark> element is fused to highlight or draw attention without changing its importance or emphasis. The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. Below are the different use cases.

  • Indicating a searched-for word or phrase in a search results page.
  • Indicating a specific code of interest in a code sample such as a change that’s discussed in the surrounding text.
  • Highlighting part of a quotation that wasn’t emphasized in the original.

Example 

<p>While Remy and Bruce did a masterful job on <mark>&lt;cite&gt;</mark>Introducing
HTML5<mark>&lt;/cite&gt;</mark>, I’m not sure about that shade of brown.</p>

While Remy and Bruce did a masterful job on <cite>Introducing HTML5</cite>, I’m not sure about that shade of brown.

Cookies will continue to be an effective tool for the foreseeable future, but they have some drawbacks.

  • Capacity limitations: Cookies are limited to about 4 KB of data, which is not large, although we can create more than 30 cookies per site. (The actual maximum limit depends on which browsers you are targeting; the average is between 30 and 50.)
  • Overhead: Every cookie is sent with each HTTP request/response made, regardless of whether the values are needed. This is often true even for requests for static content (such images, css files, and js files), which can create heavier-than-necessary HTTP messages.

Contenteditable attribute allows the user to edit any of the text contained within the element, including its children. User can edit a simple to-do list and store them using local storage.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>untitled</title>
</head>
<body>
   <h2> To-Do List </h2>
    <ul contenteditable="true">
       <li> Break mechanical cab driver. </li>
       <li> Drive to abandoned factory
       <li> Watch video of self </li>
    </ul>
</body>
</html>

Below are the best practices to be followed to create a practical and maintainable CSS.

  • Think in terms of components, not pages.
  • Think about types of things, not individual things.
  • Prefer classes to IDs.
  • Create composable classes.
  • Use descendent selectors to avoid redundant classes.
  • Keep the selectors as short as possible.
  • Order the CSS rules loosely by specificity.
  • Prefer percentages for internal layout dimensions.

Advanced

HTML5 has been developed considering current and future browser development and past, present, and future web development work. Due to this, HTML5 gained significant momentum. Driven by practicality, it has emerged as the W3C’s choice for accelerated development.

HTML5 is backward compatible and it contains all the features of the HTML4 spec, though with a few changes and improvements. It also contains additional capabilities for building dynamic web applications and creating higher quality markup.

Features of HTML5

  • New Semantic elements to allow us to define more parts of our markup unambiguously and semantically rather than using lots of classes and IDs.
  • APIs for adding video, audio, scriptable graphics, and other rich application type content to our sites.
  • HTML5 has been deliberately built to compete with proprietary plug-ins such as Flash and Silverlight.
  • New features for standardizing functionality that we already built in bespoke, hacky ways. Server-sent updates and form validation spring to mind immediately.
  • Microdata: Microdata allows machine-readable data to be embedded in HTML documents so that browsers and search engines can extract data from the page.  
  • Web Workers: Allows a JavaScript operation to work in the background without interfering with the user’s browsing.
  • Web Storage: This is a more powerful form of a cookie. It can store a large amount of data on the client side. It can store up to 5MB of data, whereas a cookie is limited to about 4KB.
  • Web Sockets: Allows pages to use the WebSocket protocol to send two-way messages between a browser and a server.
  • Cross-document and channel messaging: Cross-document messaging provides a capability to exchange documents regardless of the source domain and without enabling cross-site attacks. Channel messaging uses independent pieces of code blocks to communicate directly.
  • Server sent events: Using this feature, push notifications can be sent from a server to a client browser as DOM events.
  • New features to plug gaps in the functionality we traditionally had available in open standards, such as defining how browsers should handle markup errors, allowing web apps to work offline, allowing us to use always-open socket connections for app data transfer, and again, audio, video and scriptable images (canvas).

HTML5 introduces more than a dozen new input types for forms. The new input types provide dual benefits

  • Less development time
  • Improved user experience.   

Below are the new input types and it’s usage.

Search: Search is the most common action perform on the web every day. Search is not only for Google, Bing, or Yahoo, but it can be a field on e-commerce site we make a purchase from on the web, on Wikipedia, and even on a personal blog. The syntax for Search is

<input type="search" name="search">

Email:  Email input type is no different from a standard text input type but it allows one or more e-mail addresses to be entered with the required attribute. The browser looks for patterns to ensure a valid e-mail address has been entered. The syntax for Email is

<input type="email" name="email" required>

The URL input type is for web addresses.  The browser will carry out simple validation and present an error message on form submission. This is likely to include looking for forward slashes, periods, and spaces and possibly detecting a valid top-level domain (such as .com or .co.uk).  It also supports multiple addresses. The syntax for Url is

<input type="url" name="url" required>

Tel: tel does not have any particular syntax enforced. Phone numbers differ around the world, making it difficult to guarantee any type of specific notation except for allowing only numbers and perhaps a + symbol to be entered.  Validation against specific phone number format can be done using client-side validation. The syntax for tel is

<input type="tel" name="tel" id="tel" required>

Number: Number is used for specifying a numerical value. It, Safari, and Chrome, number input is rendered as a spinbox control whereby the user can click the arrows to move up or down or enter directly into the field. Firefox, on the other hand, renders the field like a standard text box. Support for type="number" will be in IE 10 also.  With the additional attributes min, max, and step, we can change the default step value of this spinbox control as well as set minimum, maximum, and starting values (using the standard HTML value attribute). The syntax for number is

<input type="number" min="5" max="18" step="0.5" value="9" name="shoe-size" >

Range: The Range input type is similar to number but more specific. It represents a numerical value within a given range. In Opera, Safari, and Chrome, type="range" renders as a slider. The syntax for range is

<input id="skill" type="range" min="1" max="100" value="0">

Date: HTML5 provides date control which provides a date picker functionality with is integrated with the browser without any external libraries.  Date control allows to select a single date; select a week, month, time, date and time, and even date and time with a time zone using the different input types. The markup is pretty straightforward. The syntax for Date is

<input id="dob" name="dob" type="date">

Also, using the min and max attributes to ensure the user can only choose from a specified date range.

<input id="startdate" name="startdate" min="2012-01-01" max="2013-01-01" type="date"> 

Month: Month is used to select a particular month on the web page. It can be used for a credit card expiry date. The syntax for month is

<input id="expiry" name="expiry" type="month" required>

Week: week is used to select a particular week in a month. The syntax for week is

<input id="vacation" name="vacation" type="week">

time : time renders a spinbox for selecting the precise time. The syntax for time is

<input id="exit-time" name="exit-time" type="time">

DateTime: We can combine the date and time by using type="datetime" for specifying a precise time on a given day. The syntax for datetime is

<input id="entry-day-time" name="entry-day-time" type="datetime">

Datetime-local: Using datetime-local, user can select a precise time on a given day with a local time zone variation. The syntax for datetime-local is

<input id="arrival-time" name="arrival-time " type="datetime-local">

Color: The Color input type allows the user to select a color and returns the hex value for that color. It is anticipated that users will either be able to type the value or select from a color picker,. The syntax for color is

<input id="color" name="color" type="color"> 

Modernizr is an open source, MIT-licensed JavaScript library that detects support for many HTML5 & CSS3 features. You should always use the latest version. To use it, include the following highlighted <script> element at the top of your page.

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>Dive Into HTML5</title>
  <script src="modernizr.min.js"></script>
</head>
<body></body>
</html>

Following are the Apis supported by Modernizr

  • Modernizr.canvas attribute is used to detect support for the canvas API. 
  • Modernizr.canvastext attribute is used to detect support for the canvas text API.
  • Modernizr.video attribute is used to detect support for HTML5 video. 
  • Modernizr.localstorage attribute is used to detect support for HTML5 local storage. 
  • Modernizr.webworkers attribute is used to detect support for web workers.
  • Modernizr.applicationcache is used to detect support for offline web applications.

• Modernizr.geolocation is used to detect support for the geolocation API.

The Web is based on hyperlinks. Each Web page contains active links to other pages, which in turn link to even more pages, until presumably the entire Web (or at least a great chunk of it) is bound together. In fact, that’s where the name “web” comes from. Hyperlinks can connect to other places on a Web page, to other pages within the Web site, to pages outside the site, and to many types of Web and non-Web content.

Scenario 1: Hyperlinking to a Web Page.

The syntax for a hyperlink starts with <a> tag and uses an href=attribute which provides the URL or path to a destination.

E.g <a href="http://www.microsoft.com">

This is followed by the text that will appear underlined as the link text that user click, or by a reference to the image that will serve as a hyperlink

E.g Visit <a href="http://www.microsoft.com">Microsoft.com</a> for the latest information.

Scenario 2: Using Partial Paths and Filenames

In order to link to a specific page, the complete file name should be specified. Example, To provide a direct link to the page where users can download Windows Media Player, it should have the following tag:

<a href="http://www.microsoft.com/windows/windowsmedia/player/download/download.aspx">Download Windows Media Player</a>

Scenario 3: Using Relative and Absolute Paths

Paths that contain a complete address that anyone can use to get to that page are called absolute paths. Absolute paths are very reliable, but they are also long and awkward to type.

E.g <a href="http://www.microsoft.com/articles/Windows10.htm">Windows 10</a>

Instead of providing the full path only the destination file is provided, it is called a relative path. Below are the relative path examples.

<a href=" Windows10.htm">Windows 10</a>
<a href=“articles/ Windows10.htm">Windows 10</a>

Scenario 4: Setting a Target Window

To direct the hyperlink to open a page in a new window, add the attribute target=″_blank″ to the <a> tag. For example, to open the foliage.htm file in a new window, the tag would be structured like this:

<a href=" Windows10.htm " target="_blank">Windows10</a>

Scenario 5: Hyperlinking to an E-Mail Address

Hyperlinks can point not only to web pages but also to email address. Email hyperlinks are useful to send a message to a particular person directly.

<a href="mailto:support@microsoft.com">Contact Us</a>

Scenario 6: Creating and Hyperlinking to Anchors

An anchor is a marker within an HTML document, roughly analogous to a bookmark in a Word document. Define a specific location in the document with an anchor name, and then hyperlink directly to that anchor. Anchors are most valuable in long documents with multiple sections. They provide a means for users to jump directly to whatever section they want rather than having to read or scroll through the entire document.  

E.g

<div id="top">conclusion </div>
    <a href="#conclusion">View the Conclusion</a> # plays a critical for identifying the section

<section> is best used as a sub-section of an <article> and should always contain and enclose a heading, something like the following:

  • Don’t use <section> as a target for styling or scripting; use a <div> for that
  • Don’t use <section> if <article>, <aside>, or <nav> is more appropriate.
  • Don’t use <section> unless there is naturally a heading at the start of the section.
<article>
<h1>A heading, any level from h1 to h6</h1>
<section>  
<h1>A heading, any level from h1 to h6</h1>some content
</section>
<section>
<h1>A heading, any level from h1 to h6</h1>some content
</section>
 </article> 

An <article> is a stand-alone item, such as a self-contained piece of information that could be lifted from the page and published in a forum, magazine, RSS feed, or newspaper. It should contain and enclose a heading (h1 to h6) and it can contain two or more sections. The key words are STAND ALONE.

While grouping headings resulted in problems with the outline of a document; this problem is called phantom nodes.  To avoid the phantom nodes, use <hgroup> to group two or more headings (h1, h2, h3 ,h4, h5, and h6).

<hgroup></hgroup> is a container for two or more headings (h1, h2, h3 ,h4, h5, and h6). It indicates that the headings are closely related, so it will be used to group together headings with subheadings, titles, and subtitles.  Using <hgroup> avoids phantom nodes problem because it combines the two headings into one node. The <hgroup> tags can only contain headings.

The following is an example:

Example

<!DOCTYPE html>
<html>
    <head>
          <meta charset ="UTF-8">
          <title>Images</title>
    <style type="text/css">
       h1 { font-size:160%; font-weight:bold; margin-top:5px; margin-bottom:0; }
       h2 { font-size:130%; font-weight:bold; margin-top:0; margin-bottom:5px; }
       article { width:445px; text-align:left;  }
    </head>
    <body>
         <article> <hgroup> <h1>I put our holiday dates and address on a social network</h1>
               <h2>An idiot's tale</h2>  </hgroup> <p>We returned to a ransacked house, even the furniture was taken.<br> Your friend, <br>Sreekanth</p>
          </article>
    <body>
</html>

Output

Rewrite the following code to apply the caption “This is an image of something interesting’

<img src="path/to/image" alt="About image" />
<p>Image of Mars. </p>

There is no easy or semantic way to associate the caption, wrapped in a paragraph tag, with the image element itself.  Using HTML5 <figure> element along with <figcaption> element, we can now semantically associate captions with their image counterparts.

Example

<figure>
   <img src="path/to/image" alt="About image" />
   <figcaption>
       <p>This is an image of something interesting. </p>
   </figcaption>
</figure>

Output

Caching generally refers to the storage of web resources (HTML documents, images, and so on) in a temporary location to improve performance. Caches can be implemented by most web browsers, perimeter (intermediate) web proxies, and at the gateways of large internal networks. Transparent proxies (caches) are used by many Internet Service Providers (ISPs), reverse proxies sit in front of web servers, and the web server itself utilizes caching.

Different types of caching are explained below.

Caching by Browsers

Web browsers implement a cache to hold recently and frequently accessed resources. It is much faster to retrieve a resource from the cache than to request it again from the web server. When deciding what to cache, browsers are usually quite well behaved and respect the caching policy dictated by the server.

There are several problems with browser caching. The size of the cache tends to be quite small by default and when the cache becomes full, the algorithm to decide what to remove is crude. Commonly, the Least Recently Used (LRU) algorithm is used to purge old items.

Intermediate Caches:

The intermediate cache/proxy is commonly used by ISPs and larger organizations. When used by ISPs, it typically takes the form of a transparent caching proxy that silently intercepts HTTP traffic. When the client makes a request, the proxy intercepts it and checks its local cache for a copy of the resource. If none is found, it makes the request on the client’s behalf and then relays this back to the client, caching a copy itself in the process. When another client on the same ISP requests the same resource, a cached copy is returned.

Reverse Proxies Browser caches and intermediate proxies are generally for the benefit of the client, reverse proxies are usually used for the benefit of the web server. These proxies sit in front of the web server and have two purposes (although sometimes they are used for just one of these reasons): caching and load balancing. For caching, they can be used to lighten the load on the back-end web server by serving up cached versions of dynamically generated pages (thus cutting CPU usage). For load balancing, they can be used for load-balancing multiple back-end web servers.

Below are the different ways to control the cache.

Controlling Caching

Conditional GETs: Send a conditional GET request, the request knows if a local, cached copy of a resource is still valid.  The “If-Modified-Since header” is sent in the request. If the server determines that the resource has been modified since the date given in this header, the resource is returned as normal. Otherwise, a 304 Not Modified status is returned.

Utilizing Cache-Control and Expires Headers: Apart from “If-Modified-Since header”, there are two more headers that can control caching: Expires and Cache-Control: max-age. These headers effectively say to the client, “This resource expires on such-and-such a date. Until then, use your locally cached copy (if you have one).” The result is that the client doesn’t need to issue a conditional GET.

ExpiresByType image/gif "access plus 2 months“

ExpiresByType image/jpeg "access plus 2 months“

Minification is the act to strip out unnecessary characters from code to reduce the size, and a minifier is the tool that does it. Most often, the term is applied to JavaScript, but as you shall see, the technique can also be used on JavaScript, CSS and HTML.

JavaScript Minification: JavaScript offers the most potential for minification. Aside from removing white spaces and comments, Windows-style line breaks (CRLF) can be converted to UNIX-style breaks (LF), and variable names can be shortened.

function toggle(elementID) {   
     if ( document.getElementById(elementID).style.display != 'none’ ) {  
        document.getElementById(elementID).style.display  = 'none';
     } else {  
         document.getElementById(elementID).style.display = '';  
    }}
function toggle(elementID) {
   var el = document.getElementById(elementID);   
   if ( el.style.display != 'none' ) {       
        el.style.display = 'none’;
    } else {     
   el.style.display = '';
}}

CSS Minification : Many of the minification techniques outlined for JavaScript minification are also applicable to CSS — the removal of extra whitespaces, removal of comments, and conversion of CRLF to LF.

.myclass {    
           margin-left: 10px;  
            margin-right: 10px;
           margin-bottom: 20px;
           margin-top: 20px;}
myclass { margin: 20px 10px;}

Html Minification: Html minification is newer and is still experimental. Following are the available options:

  • Remove comments.
  • Remove comments from JavaScript and CSS blocks.
  • Remove character data (CDATA) blocks from CSS and JavaScript.
  • Collapse whitespace.
  • Collapse boolean attributes (for example, selected="selected").
  • Remove attribute quotes (when it is safe to do so).
  • Remove redundant attributes (for example, language="JavaScript").
  • Use short doctype.
  • Remove empty attributes (for example, title="").
  • Remove optional closing tags.
  • Remove empty elements such as <p></p>.
  • Remove type="text/javascript" from inline script.

OPTIMIZING IMAGES: Implementing compression on an image with our impacting the quality can reduce the size of the image.  There are different ways to improve the performance of a web page when images are present.

  • Reduce the Image size
  • Eliminating the Http request for favicon instead use Data URI
  • Use Lazy loading
  • Avoid empty src attributes
  • Setting appropriate width and height attributes

HTML5 introduced different approaches for web developers to save persistent content on a user’s machine namely Local Storage, aka Web Storage and WebSQL Storage. Local Storage feature is easy and here is the syntax for storing and retrieving.

<script>
localStorage.setItem(“Name”, “Sreekanth”);
var firstName = localStorage.getItem(“Name”);
</script>

Information is stored as key-value pair and can be easily stored and retrieved using a simple API. Event handlers can also be registered to monitor for changes to localStorage values.  localStorage is well supported in modern browsers and it is consistently supported across desktop and mobile browsers.

The localStorage object provides much more space than was available with older tools. Modern browsers support a minimum of 5 MB of data, which is substantially more than is allowed through cookies (which are limited to 4 KB each).

If the storage limit is reached, or if the user manually turns off storage capabilities, QuotaExceededError exception is thrown. Below code is to be used to prevent an exception to the user.

try {
localStorage.setItem('firstName', $('#firstName').val());
} catch(e) {
// degrade gracefully
}

Currently, only string values can be stored in web storage, but sometimes we might need to store arrays or JavaScript objects. To accomplish this,  we need to use JavaScript Object Notation (JSON) utility methods.

The following example creates a JSON object and uses the stringify() method to convert the value to a string that can then be placed in web storage and use the parse() method to deserialize a new instance of the object from the string representation of the object that was stored

var person = { firstName: sreekanth', lastName: boya' };
localStorage.setItem(‘person', JSON.stringify(person));  
var person = JSON.parse(localStorage.getItem(‘person '));

localStorage is designed to retain data across multiple sessions.

sessionStorage is a Web Storage to store the data. It retains data for a single session only. If the user closes the browser window, records stored are automatically cleared. This is an important advantage because only a limited amount of space is available.

SessionStorage is firmly dedicated to their respective browsing contexts. sessionStorage has a context that, by design, is extremely confined. It’s limited to a single browser tab or window. Its data cannot be passed from one tab to the next. However, the data can be shared among any <iframe> elements that exist on the page.

Code to show the usage of sessionStorage

window.onload = function() {
     var currDate = new Date();
     sessionStorage.setItem("currenttime", currDate.toLocaleString());
}
function updateHTML() {
document.getElementById("currenttime").innerHTML= sessionStorage.getItem("currenttime");
}

XSS Attack: XSS refers to client-side code injection attack where an attacker can execute malicious scripts by making use of unvalidated or unencoded user inputs in web applications. This malicious scripts may attempt to steal sensitive information from the user visiting the website. We need to prevent attack by filtering user inputs using blacklisting(not allowing users to input character sequences such as <, >, <script> etc.).

Different type of XSS attacks :

Stored or Type 1 XSS attacks: Stored XSS attacks in which the supplied malicious input from the attacker is persisted and stored in the back-end database or repository. Whenever that content is retrieved and rendered to be displayed on the web page, the browser is completely unaware of it and it either executes the malicious JavaScript that comes from the database or renders the malicious HTML markup, instead of displaying it as text. The stored XSS will remain permanently in the database and will impact all users visiting the affected web page.

Reflected or Type 2 XSS attacks: Reflected XSS attacks are the second type of XSS attack vector, in which the malicious XSS payload is not stored in the database table for persistence, but is still injected in some parameter of the web page that gets rendered back to the user. The browser, unaware of this change, simply either renders the injected malicious HTML or executes the injected malicious Javascript code, again resulting in the user's data being compromised.

DOM-based or Type 0 XSS attacks: A document object model-based XSS is the third category of XSS attacks. Here, the XSS payload is not sent to the server, but due to implementation flaws and changing the state/DOM of the web page with the help of client-side JavaScript, an attacker paces the payload that gets picked up with the JavaScript responsible for manipulating the state of the web page.

Prevention Methods: 

✓ Output encoding: Escaping any character a user enters before displaying it.

✓ Filtering inputs using whitelisting: Only allow characters (e.g, A–Z and 0–9) to be entered.

✓ Filtering inputs using blacklisting: Not allowing a user to enter character sequences such as <script> or even < and > characters.

Placeholder: The placeholder attribute can only contain text, not HTML markup.   However, there are some vendor-specific CSS extensions that allow you to style the placeholder text in some browsers.  Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

Here’s how you can include placeholder text in your own web forms:

<form>
 <input name="q" placeholder="Go to a Website">
 <input type="submit" value="Search">
</form>

You can use Microsoft Internet Explorer conditional comments to load a style sheet created exclusively for Internet Explorer. You can place a conditional comment in <head> after all links to other style sheets. Inside the conditional comment, you can place a link to a style sheet. I call this the conditional style sheet. Since the conditional stylesheet comes last, it overrides previously loaded styles. You can create a separate conditional stylesheet for Internet Explorer 6, and if necessary you can create one for Internet Explorer 7. You can include styles in this stylesheet to compensate for different behaviors and bugs.

The following pattern loads two conditional style sheets. The first is for Internet Explorer versions 6 and earlier. The second is for Internet Explorer 7 and higher. Internet Explorer 7 fixes most of the bugs in Internet Explorer 6, but there are still a number of CSS features that it does not implement, such as the content property.

HTML

<!--[if lte IE 6]>
<link rel="stylesheet" href="ie6.css" media="all"
type="text/css" />
<![endif]-->
<!--[if gt IE 6]>
<link rel="stylesheet" href="ie.css" media="all"
type="text/css" />
<![endif]-->

Markup a document with block elements to identify its structure. There is meaning in structure, and HTML markup is most meaningful when its structure reflects the hierarchy and relationships of a document’s topics.

Because a parent element contains child elements, they are related structurally. This implies their content is related. For example, a child’s content is typically a subtopic of its parent’s topic, and siblings typically have related subtopics. Implicit in the hierarchical nature of HTML is the assumption that document organization is hierarchical.

Structural blocks may contain block elements only. They have structural meaning, but they have little semantic meaning. In other words, they do not tell you what something is; they tell you how it is organized.

There are four major structural block elements (<ol>, <ul>, <dl>, and <table>) with nine supporting structural elements (<li>, <dt>, <dd>, <caption>, <thead>, <tfoot>, <tbody>, <colgroup>, and <col>)

HTML supplies the class and id attributes for these purposes. We can assign a class and an id to any element. An ID and class name cannot include a space. It must start with a letter and may contain letters, numbers, the underscore (_), and the dash (-). Since CSS selectors are case-sensitive when using XHTML, it is a common practice to use lowercase class and ID names.

#id { STYLES }
*.class { STYLES }

Apply styles to chosen class or ID as follows:

  • Use the type selector to select all elements of a particular type. The type selector is the element’s name without the less-than and greater-than signs.
  • Use the class selector to select all elements that you have assigned to a class. The class selector is the period followed by the name of a class. The class selector is added to the end of a type selector. You can add it onto the end of the universal selector, *, to select all elements in the document that have a matching class, such as *.my-class1. You can also use the class selector all by itself, such as .my-class1, which is a shortcut for *.my-class1.
  • Use the ID selector to select all elements in the document assigned to that ID. Each element has one ID, which should be unique in a document.

HTML

  • type { STYLES }
  • *.class { STYLES }
  • #id { STYLES }

Below are the few best practices to improve the performance of the page load time.

  • Make Fewer HTTP Requests
    • Implementing parallel HTTP requests will improve performance.
    • Combining smaller resource files and creating a single file will reduce the number of HTTP requests.
    • Use Image sprites to combined image files and delivering content more quickly over the browser’s relatively low number of parallel connections.
  • Use a Content Delivery Network (CDN)
    • Putting all that static content close to the user can really speed up performance.
  • Avoid Empty src or href Attributes
    • Avoid creating an img element with an empty src attribute and then dynamically assign the value of the src attribute during page load with JavaScript. With this approach, the elements always get evaluated before scripts get run. The browser tries to evaluate that empty attribute and creates an HTTP request to do so.
    • A similar pattern and problem appear for href attributes, usually in anchor elements. If the href attribute is blank, the browser sends an HTTP request to the server when the user triggers the interaction. That doesn’t affect page load time, but it does create needless traffic on the servers,
    • wasting bandwidth and potentially slowing delivery for all visitors. The simple fix for this problem is to set the value of the href attribute to a JavaScript command like <a href="javascript:;" class="triggerName">Trigger</a>
  • Add Expires Headers
    • Adding an Expires header with a date far in future to all your static components (images, stylesheets, scripts, flash, PDF, and so on) lets the static content be cached by browsers. The browsers won’t have to fetch the static content for subsequent visits and they’ll have a much faster loading time.

E.g: Expires: Wed, 1 Jan 2020 00:00:00 GMT

  • Compress Components with GZIP
    • Using the “Accept-Encoding” header, the content in the HTTP request can be compressed. Such a header appears as below

               Accept-Encoding: gzip, deflate

            The header specifies two kinds of compression. GZIP is more common because it is the most effective compression scheme available. GZIP reduces the size of a response by about 70%.

  • Put CSS at the Top

If the page contains style information, put that information at the top (in the head element). To avoid

Redrawing many web browsers won’t start rendering a page until the browser has all the style information.

  • Put JavaScript at the Bottom
  • Avoid CSS Expressions
  • Remove Unused CSS
  • Minify JavaScript and CSS
  • Minimize Redrawing

Description

Are you worried about how you would excel in your next HTML Developer job interview and what exactly you need to crack the same? If yes, then look no further. Our team, formed by formerly experienced interviewers, have created 30 HTML interview questions and answers, with 12 of them being of intermediate-level and 18 of advanced-level to help you succeed in answering all the tricky questions with assurance and confidence.
Levels