Amfas Tech | Technology, Blogging & Internet Marketing: JavaScript

Everything You Need to Know Before Starting to Work with JavaScript & SEO

For most professionals out there, SEO optimization practices always meant working with plain text versions of content. However, as the technology continues to evolve, this is no longer the case, because SEO requires understanding technical knowledge to work with dynamically generated content, like through JavaScript.

Optimization of pages built with JavaScript represents a great example of the need for technical knowledge for professionals. To be able to provide helpful advice to developers and ensure that they follow the best SEO practices, professionals need to understand the essentials of JavaScript search engine optimization.

Are you also an SEO professional looking to enhance your knowledge of JavaScript SEO? It’s certainly a good knowledge to have because you need to know the relationship between Google and the content rendered by JavaScript to be able to improve the latter’s performance.

In this article, we are going to give you everything you need to know before starting to work JavaScript and SEO so you have a perfect understanding of how a website using JavaScript can be properly crawled and indexed, and ranked high on Google.

Let’s begin.

What is JavaScript? How does it Work?

JavaScript is one of the most popular programming languages that can create websites that engage visitors in a great way. The list of websites using JavaScript includes such well-known platforms such as Google. Wikipedia, Facebook, YouTube, Reddit, and Amazon. The ability of this language to provide a great user experience using animations, smooth content transitions and page transitions, zoom effects, and other effects made it very popular among web developers.

In fact, here’s a graph for you showing the usage of JavaScript, courtesy of BuiltWith Trends.



JavaScript utilizes frameworks to create beautiful, interactive web pages by managing the performance of page elements. These frameworks run inside an Internet browser; this means that you load a page using your browser, it uses its built-in interpreter that finds a JavaScript code on the page and runs it.

Can Google Crawl JavaScript?

According to Google’s Webmaster Central Blog, the search engine has gotten pretty good at understanding pages built with JavaScript. Even though the developers at Google would have us think that we shouldn’t worry about JavaScript and website crawling because they’ll take care of everything, this is not entirely true.

Well, newsflash: Google does not handle JavaScript perfectly no matter what its developers say on it blog. In fact, they even kinda admitted that on the aforementioned page of the Webmaster Central Blog. Specifically, they wrote that (the following is an excerpt from the Blog):

Sometimes the JavaScript may be too complex or arcane for us to execute, in which case we can’t render the page fully and accurately.

Some JavaScript removes content from the page rather than adding, which prevents us from indexing the content.

As you can see, saying that Google can crawl JavaScript-rendered content is not exactly true. Clearly, there are some limitations and caveats when it comes to crawling and they don’t disappear even after users follow Google’s advice to “follow the principles of progressive enhancement.”

What is the Difference between Client-Side Rendering and Server-Side Rendering?

Before starting to work with SEO for JavaScript, you need to know two critical concepts: server-side (back-end) and client-side (front-end) rendering.

The first respective process happens before a web page is loaded into a browser. This is a traditional approach in which a browser receives an HTML that completely describes the requested page. Typically, Google and other search engines do not have any problems with server-side rendering. The copy of content is there, so all a search engine or browser have to is to download CSS (Cascading Style Sheet, a programming language that describes how HTML elements are displayed on the screen) and “paint” the page’s content on the screen.

On the other hand, client-side rendering uses a different approach, and Google has some problems with adapting to it. In this case, a browser or a search engine receives a blank HTML page without any content. Next, JavaScript downloads the copy of the content from the server, refreshes your screen, and alters the DOM (Document Object Model).

Simply explained, DOM is the process that browsers use after receiving the HTML copy of content to render the page. You can actually see DOM when you click on “Inspect Element” in Firefox.




How JavaScript affects SEO?

Using JavaScript allows to achieve higher versatility, faster server load, more loading time speed, and easier implementation. That’s great news for SEO! With website speed being one of the most important ranking factors, you can certainly use these advantages to get ahead of the competition.

Unfortunately, JavaScript also brings some problems. For example, many struggle to SEO-optimize the content that uses JavaScript.

Naturally, a question arises: should an SEO professional know how JavaScript affects Google ranking. The answer, is yes, of course.

The reason why should know how to make your JavaScript more SEO-friendly is that Google does not take care of everything on its end, so most of the problems your JavaScript-built website will have may be a result of a lack of optimization, not Google’s inability to handle JavaScript properly.

Also, here’s what Google had to say to explain that:

What should you be concerned about as a SEO professional?


The main job for SEO professionals is to take care of three important things related to JavaScript on their websites:

  • Crawlability. The ability of search bots to crawl your website.
  • Obtainability. The ability of search bots to obtain information regarding your website and parse through its content.
  • Critical Rendering Path. According to Google, this term refers to “prioritizing the display of content that relates to the current user action.”

Crawlability

This term refers to optimizing the website for Google’s crawler bots that read and categorize our website, thus deciding where it should be displayed in search results.

To make sure that crawler bots do their job, you should clean up and optimize the site code and structure, because they are critical for the success of crawling.

Let’s now see what can prevent Google from crawling your website: 

The HTTP Header Saying That a Page Does Not Exist

The initiation of crawling begins only if a crawler took a look at HTTP header that confirmed the existence of a certain web page by a status code. If the header says that a page does not exist, so the crawler won’t be able to crawl the website, therefore, Google will not crawl your website.

To ensure that bots can find all the pages on your website, you should submit XML sitemaps to Webmaster Tools. Google has all the instructions to build and submit a sitemap to them. Also, you can use free tools like XML SiteMap Generator.




In addition to the structure and hierarchy of your website, it may also contain maps for images and videos. The optimization of these maps is important to help Google crawl non-text content.

“Also, to clean your site’s architecture, you should use internal linking,” advises Mark Bledsoe, a web developer at A-Writer. “It is basically a signal for Google to understanding the architecture and importance of the pages.”

 Image Source: Neil Patel

Its purpose is threefold:
  • Help Google with website navigation
  • Define the website’s structure and hierarchy
  • Distribute page authority and ranking.

Here’s what you should do ensure that internal linking enhances the overall search-optimized value of the website.
  • Create a lot of content. Internal linking is impossible without internal pages, so create as much quality content as you can.
  • Avoid links to top pages. Do not link to homepage and contact us page. This is too ‘salesy.’
  • Use informative links to match the context of the content. The users will use links only if they make sense to them.
  • Don’t link for the sake of linking. For example, if you have a page about social media marketing plans and a page with a car review, linking them will not make any sense because the content on the first respective page is totally irrelevant to the content on the second page.

Robots.Txt File Can Block the Crawler

If this happens, no search engine will ever find your website or a certain page.

Google defines robots.txt as “a file at the root of your website that indicates those parts of your website you don’t want accessed by search engine crawlers.”

An example of a simple robots.txt file for a website built with WordPress:

User-agent: *
Disallow: /wp-admin/

(This example tells Google to leave /wp-admin/ directory alone).

In other words, this file has directives for Google on whether to crawl specific parts of your website. To ensure that it supplies Google with the information you need, follow these tips:

  • Robots.txt must reside in the root of your website (for example, if your website is www.example.com, you should place it at www.example.com/robots.txt).
  • The file is valid only for the full domain it resides on, including https
  • Be super attentive when making changes. Remember: this file can prevent your website from being found by Google.
  • Avoid using the crawl-delay directive for Google as much as you can.
  • Test your robots.txt file with a free tool from Google.


Robots Meta Tag Can Block Google, too

Since this tag tells search engines what to follow and what not to follow, it can block them from indexing the page. While this still allows them to crawl that page, it makes it impossible to index it.

The following are robots meta tag values and how Google interprets it, according to Webmaster Central Blog:

  • NOINDEX – this tag blocks Google from indexing the page
  • NOFOLLOW – this tag prevents Google from following any links on the page
  • NOSNIPPET – this tag prevents a description of the website from appearing in search engine’s results
  • NOARCHIVE – this tag blocks a cached copy of the webpage from being available to search engines.
  • NONE – equivalent to “NONINDEX, NOFOLLOW.”

To ensure no limits and an inadvertent blockage of content, some web developers use the following meta tag:

Obtainability

Google and other search engines use headless browsing (action of fetching webpages without the user interface) to render the ROM to obtain as much information about the content and the user’s experience. In other words, they process JavaScript and utilize the DOM instead of HTML.

To ensure that Google finds and ranks the website, it is important to get a good understanding of how it crawls and interacts with the website’s content. Here are some facts you need to know:

  • If JavaScript loading time exceeds five seconds, Google may not be seeing your website at all
  • If JavaScript has some errors, Google may miss some pages
  • Crawling bots do not see actions that your site requires from users.

How to Ensure that Google Gets Your Content

There are a lot of speculations about how Google interacts with different libraries and frameworks of JavaScript. The studies like this one described on Elephate blog found that the search engine had different patterns of interaction with different JavaScript frameworks and libraries.

Since no one can guarantee that Google loves your JavaScript-built website, testing various aspects of its performance and content is a good idea. So, test the pages on your website to ensure that Google can index them.

Critical Rendering Path

The last thing on our list of things that SEO professionals should be concerned about has to do with the user experience. A search engine’s critical rendering path is tailored to enhancing user experience because it aims to deliver it by loading pages faster.

Here are some examples of how it affects a website’s performance, courtesy of Google.



However, you may interfere with this path if your JavaScript files are blocking your website’s or a specific page’s ability to load. Therefore, testing for these files is very important.

Wrapping Up

For you as an SEO professional, the most important thing about JavaScript and SEO is that you have to pay close attention to the factors described in this article. They can help you resolve nearly all issues and questions you can have when trying to optimize your JavaScript content for Google or any other search engine.

Oh, and one more thing for you: optimization and implementation of JavaScript come with different risks, so expect to run into something that doesn’t work properly at some point. You just need to take your time and test everything, and Google will do the rest.


About Author: Audrey is a passionate blogger and marketer at college-paper.org. Her areas of interests are very wide, but mostly she writes about content marketing and business relations. Her aim is to engage people to self-growth and staying motivated.
Continue Reading

What Are The Top Mobile JavaScript Frameworks and Why?

The popularity of JavaScript is keeping rising. And last year, we have observed some of the wonderful changes as AngularJS upgrade entirely, development of ECMAScript, launching of Angular 2, two major updates of Node.js. etc. Therefore, there is a lot more that we can expect from 2017 as more and more people are looking forward to using JavaScript.


As of May 2017, GitHub reveals that there are approximately 1.1 million JavaScript projects and more than 500 thousand usable packages on npmjs.org with approximately 10 billion downloads every single month. Lately, IBM declared JavaScript as the best programming language to learn in 2017.


As we all know that JavaScript becomes a promising programming language for web development, but what about mobile app development? Does it fruitful for the mobile app too? In this post, you can find about the top mobile JavaScript frameworks and why they are leading on top.


Top JavaScript Frameworks For Mobile App Development

React Native

React Native is the most advanced native framework that allows to developing mobile apps using JavaScript only. The framework makes use of the same design as React, allows users to compose a rich mobile UI from declarative components.


Using this framework, users can build native Android and iOS applications in JavaScript without learning Java or Objective-C programming languages. It uses the exact same fundamental UI building blocks as regular iOS and Android applications. You can keep those building blocks together using JavaScript and React.


Top Features of React Native Framework:

  • The framework has own DOM, so this framework calculates changes required in advance and updates accordingly.
  • React Native mainly focuses on UI, giving responsive interface, so keep an application running smooth and without any interruptions.
  • The framework runs on the server and virtual DOM reduced to the browser, resulting page allows search engine indexing with ease and favors all SEO processes.


Ionic

Iconic is the most powerful, free and open source mobile SDK that can be used to develop native and progressive web applications with ease. Considered as the easiest framework to learn, this framework is a great choice for all the less experienced developers, who are looking forward to developing an app. Moreover, the framework has a completely great community and documentation, so again it is beneficial for the newbie developers.


A Range of Iconic Features:

  • Users can build their apps, customize them for Android or iOS and deploy through Cordova.
  • The framework includes mobile components, interactive paradigms, typography and an extensible base theme.
  • Developers, who are using Iconic, can control the scroll-view so that they can get the scroll position and get information about the current scroll-view instances.


Angular JS

Angular JS is the widely used JavaScript framework for hybrid mobile app development as this is one such framework that offers seamless native-like experiences.


Currently, single page web applications are highly popular, so Angular JS is a right tool that accomplishes it using commands. Directives are extremely helpful when it comes to adding reusable code in the app to incorporate dynamic functionality.


This framework offers all the features that Bootstrap 3 is missing. Moreover, it also comes with top components like overlays, sidebars, switches, absolute positioned navigation bars, etc.


Top Features of Angular JS:

  • Offers Easy testing of any app part and two-way data binding
  • It is the most JS framework for SPAs (Single-Page Applications)
  • They framework claims to have the largest community of developers
  • It offers the best option for enterprise-based apps with high-standards for code readability.


jQuery Mobile

jQuery Mobile framework is also a high-end framework that follows the write less, do more mantra and take it to the next level. Rather than writing a completely new and unique app for each mobile device of OS, this framework allows you to design a single highly-branded responsive website or app that work on all popular smartphone, desktop and tablet platforms.


jQuery Mobile Framework Features:

  • jQuery framework is built on top of jQuery core, so it has a minimal learning curve for people that are already familiar with jQuery syntax.
  • Theming framework, allowing the creation of custom themes.
  • HTML5-driven configuration for laying out pages with minimal scripting.
  • UI widgets, which are touch-optimized and platform agnostic.


Vue.js

Vue.js is an extremely lightweight progressive framework that can be used for building user interfaces. The framework’s core provides a React-like virtual DOM-powered view layer that can be integrated with some of the other obtainable libraries. However, the framework has an ability to power single-page applications.


The framework makes use of an HTML template syntax to bind the DOM to instance data. In addition to this, models are plain JavaScript objects that update the view when data is changed. Some of the additional tools also offer facilities for routing, animations, state management, scaffolding, etc.


Vue.js Framework Features:

Simple to get started with high level of among developers.

  • All the above-mentioned JavaScript mobile app development frameworks can be used easily without having in-depth knowledge of objective to develop iOS app or Java to develop an Android app. Using these best JavaScript frameworks developer satisfaction
  • Rapid adoption and increasing popularity
  • Offers good performance with small dependency


Why these frameworks are popular?

These mentioned frameworks have already reshaped the entire way how JavaScript collaborates with HTML and CSS in order to compile views both in browsers and on native platforms. You can notice that various mobile app development companies are using these JavaScript frameworks to develop a high-end mobile app that performs exceptionally.



Author Bio: Jyoti Bharwani is a Content Manager at Space-O Technologies. She has a keen interest in writing related to mobile app development and app marketing. In free time, she prefers to read non-fiction books. To follow her on Twitter.

Continue Reading

Reading Mode Widget/Plugin for Blogger and WordPress

Blogging is not all about creating content. It is also about gaining loyal readers. Apart from the quality of the content you provide, the visibility and readability of the content also matters. To be specific, readability includes font styles, backgrounds and eye-friendly modifications to the text on the webpage.

It is however difficult to modify the styles according to individual reader’s choice. So, it is better to leave that option to the reader himself. We have developed a simple and useful snippet of HTML/JS that allows the users change the font styles and sizes according to their eye feasting taste.

Reading Mode widget for blogger wordpress from amfastech

Copy the follow snippet of code and install it on your Blogger/WordPress blog.
<script>
function myFunction() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="Open Sans";
}
function myFunction2() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="Roboto";
}
function myFunction3() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="Calibri";
}
function myFunction4() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="Calibri";
}
function myFunction5() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="PT Sans";
}
function myFunction6() {
    var x = document.getElementById("Blog1");
    x.style.fontSize = "20px";          
    x.style.color = #5E5E5E;
    x.style.fontFamily="Georgia";
}
</script>
<button type="button" onclick="myFunction()">Style 1</button>
<button type="button" onclick="myFunction2()">Style 2</button>
<button type="button" onclick="myFunction3()">Style 3</button>
<button type="button" onclick="myFunction4()">Style 4</button>
<button type="button" onclick="myFunction5()">Style 5</button>
<button type="button" onclick="myFunction6()">Style 6</button>

Customization

Change the ID “Blog1” with the blog post area of your blog. “Blog1” here is the blog post area of Blogger blog.

Change x.style.fontSize with the values of your choice.

Change x.style.color with the color of your choice.

Change x.style.fontFamily with the font family of your choice.

This is a basic script and needs to be tweaked. Any suggestions of the tweaks from your side are welcomed. You suggestions will be credited and updated in the article.
Continue Reading

Validating HTML5 forms without using JavaScript

Form validation is a process where you write code for forms and validate them using another piece of custom code. It is to make sure all inputs are filled with content they are supposed to be filled with. Validation is done in two ways: on the server side and the client side. The server side validation code runs on server to check all the fields and if the requirements are not met, the page will be reloaded with errors. The client side validation works the pretty same way. But the only difference is server side validation runs after the form submission where as client side validation runs before the form is submitted. The best kind of validation is when you do both. The client side validation gives the user an immediate response and the server side validation makes sure response wasn’t being hacked.

Generally, JavaScript is preferred technology for form validations on client side. Writing form in HTML and validating forms using JavaScript really sucks. We’ll have to check two piece of codes when any run-time errors are found. Swapping between the codes would kill your patience. HTML5 doesn’t need JavaScript for validations on client side as the new input types are introduced for validations with it.

In HTML5 the <input> tag has the ability to validate the information in the form. If it validates, proceeds to the submission and if it doesn’t, shows errors.

Let’s see the form validation in both conventional(HTML+JavaScript) and new(HTML5) ways.

Validating forms with HTML+JavaScript:

HTML Form:
<!DOCTYPE html>
<html>
<body>
<form name="myForm">Quantity (between 1 and 5):
<input max="5" min="1" value="11" name="quantity">
<input type="submit" value="Submit Query"></form>
</body>
</html>
JavaScript:
<script>
if(document.myForm.quantity.checkValidity() === false){ alert('fail'); } </script>

The above script will check the ‘quantity’ field and validates the input given in it. When the value is greater than 5, the trigger will be fired. This type of validation is a good practice if only some fields are to be validated in a form. Let us suppose we have 30 fields to be validated. Writing 30 validation lines of code isn’t necessary and it is a worst practice of coding.

You can simply write the following script that does validation of all form fields:
<script>
if(document.myForm.checkValidity() === false){ alert('fail'); }
</script>

‘myForm’ is the name of the form and it is enough to validate the fields.

Validating forms in HTML5:

Validation criteria in HTML5 is quite different and simpler than before. There is no need to use JavaScript for every small validation of the input fields. Some new ‘input’ tag attributes were introduced with HTML5. They take care of input field validations very well.

The required attribute:

The required attribute can be simply added to the input tag at the end. When the form filler misses out the field, a pop up notifies about that mandatory field to be filled.

For e.g.,
<input type="number" name="quantity" min="1" max="5" required/>

The ‘min’ and ‘max’ attributes see if the value entered is with in the range. If the out of range value is entered, it shows validation error.

The pattern attribute:

The pattern attribute is pretty slick, and is for people who write regular expressions. If you write a regular expression to the pattern attribute, your input will validate against the pattern in order to have the return value true.

For e.g.,
<input type="text" name="quantity" pattern="[0-5]{1}" />

Notice that the type was changed to text in order for the pattern to make the input invalid; we need to remove the number type, as that will supersede the validation criteria. If the type and pattern conflict (by requiring results that exclude each other), the validation criteria will never be met, and the form will never validate.

The measurable attributes:

Some input types have comparative criteria such as email, which require a strict input pattern. Other input types have attributes such as min and max that must be satisfied before the input can be considered valid. Let’s look at our first input example again:
<form name="myForm">
Quantity (between 1 and 5): <input type="number" name="quantity" min="1"
max="5" />
<input type="submit" />
</form>

In this case the number that is input must meet the min and max criteria in order to be considered valid. For example, the number 11 would not validate but the number 4 would validate. In a similar manner we have the email type:
<form name="myForm">
Enter Your Email: <input type="email" name="myEmail" />
<input type="submit" />
</form>

The email type looks for a value that meets traditional email criteria that would match a regular expression such as this:

var emailTest = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

If the value of the input doesn’t have a username, an at sign (@), and a domain, it’s considered invalid.

That's all for now! till next time! keep visiting amfastech.com
Continue Reading

3 different techniques for redirecting old websites to new URL

Whenever you wanted move your domain to a new one and you don’t want to loose the traffic that is coming for old website, you should opt for redirection. Redirecting old websites to new URL is not that hard to implement. It can also be done in client side by using simple JavaScript in the website code.




Note: Implement either of the following codes inside <head>…</head> section. Don’t forget to remove the comment tags( ‘<!—’ ,‘–>’ ,’//’and ‘/*…*/’) before you save the changes after implementation.

Method 1: Simple redirection

This method has simple code of redirecting to new website’s URL. Copy the code below and paste it in the <head>…</head> section. Replace http://www.newlocation.com with your new website’s URL.
<script type="text/javascript"> <!-- window.location="http://www.newlocation.com"; //--> </script>

Method 2: Show message before redirection

This method of redirecting features a popup message in old webpage. You can customize the message in the code below before implementing it in your website/blog. To do so, replace you will be redirected to main page in 10 sec with the text of your wish.
<script type="text/javascript"> <!-- function Redirect() { window.location="http://www.newlocation.com"; } document.write("You will be redirected to main page in 10 sec."); setTimeout('Redirect()', 10000); //--> </script>

Did you figure out why it takes 10 seconds to your page to redirect to the new URL? The part of the code setTimeout(‘Redirect()’,10000) is responsible for that delay. It actually means that the function Redirect() would be redirected after ten seconds of timeout. You can change this timeout delay also to the time you wanted.

Remember, 1 second here represented as 1000 and so it was specified as 10000 for 10 seconds of timeout. Keep that in mind before setting the timeout.

Method 3: Redirecting based on their browsers

This method of redirection allows the old website to be redirected to particular URL based on the web browser it is opened in. See the code below,
<script type="text/javascript"> <!-- var browsername=navigator.appName; if( browsername == "Netscape" ) { window.location="http://www.location.com/ns.htm"; } else if ( browsername =="Microsoft Internet Explorer") { window.location="http://www.location.com/ie.htm"; } else { window.location="http://www.location.com/other.htm"; } //--> </script>

You can customize the URL’s based on the compatibility of the browsers it is opened in. The URLs in window.location are supposed to be customizable.

Don’t forget to remove the comment tags before saving the changes after implementation of the codes above.
Continue Reading

How The Totally Different Technologies, HTML5 & JavaScript Hooked Up

HTML and JavaScript are from different planets for sure. The proof? HTML’s DNA is made of declarative markup that allows you to describe a set of nested elements that make up your pages. JavaScript, on the other hand, is made of pure algorithmic genetic material, meant for describing computations.

Are they so far apart they can’t even communicate? Of course not, because they have something in common: the DOM. Through the DOM, JavaScript can communicate with your page, and vice versa. There are a few ways to make this happen, but for now lets concentrate on one. It’s a little wormhole of sorts that allows JavaScript to get access to any element, and it’s called getElementById. Let’s see how it works...

Let’s start with a DOM. Here’s a simple DOM; it’s got a few HTML paragraphs, each with an id identifying it as the green, red or blue planet. Each paragraph has some text as well. Of course there’s a <head> element too, but we’ve left the details out to keep things simpler.

image
Now let’s use JavaScript to make things more interesting. Let’s say we want to change the greenplanet’s text from “All is well” to “Red Alert: hit by phaser fire!’ Down the road you might want to do something like this based on a user’s actions or even based on data from a web service. But we’ll get to all that; for now let’s just get the greenplanet text updated. To do that we need the element with an id of greenplanet. Here’s some code that does that:

document.getElementById("greenplanet");

-Remember the ‘document’ represents the entire page in your browser and contains the complete DOM, so we can ask it to do things like find an element with a specific id.

-getElementById: Here we’re asking the ‘document’ to get us an ‘element’ by finding the element that matches the given ‘id’.

-From the above simple code, getElementById(“greenplanet”) returns the paragraph element corresponding to “greenplanet”...

...and then the JavaScript code can do all sorts of interesting things with it..

Once getElementById gives you an element, you’re ready do something with it (like change its text to “Red Alert: hit by phaser fire!”). To do that, we typically assign the element to a variable so we can refer to the element thoughout our code; let’s do that and then change the text:

var planet = document.getElementById("greenplanet");
-We’re assigning the element to a variable named ‘planet’.
-Here’s our call to getElementById, which seeks out the “greenplanet” element and returns it.

And in our code we can now just use the variable planet to refer to our element.

planet.innerHTML = "Red Alert: hit by phaser fire!";
-We can use the innerHTML property of our planet element to change the content of the element.
-We change the content of the greenplanet element to our new text... which results in the DOM (and your page) being updated with the new text.

image

Any changes to the DOM are reflected in the browser’s rendering of the page, so you’ll see the paragraph change to contain the new content!

[Sources: Head first HTML5 programming]
Continue Reading