JQuery Hello World Example

.html()

Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

Contents:

.html() Returns: String

Description: Get the HTML contents of the first element in the set of matched elements.

version added: 1.0 .html()

This method is not available on XML documents.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

In order for the following ‘s content to be retrieved, it would have to be the first one with class=»demo-container» in the document:

div class="demo-container">
div class="demo-box">Demonstration Box div>
div>

The result would look like this:

div class="demo-box">Demonstration Box div>

This method uses the browser’s innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

Читайте также:  What is private static final string in java

Additional Notes:

  • By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, ). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.

Example:

Click a paragraph to convert it from html to text.

html>
html lang="en">
head>
meta charset="utf-8">
title>html demo title>
style>
p
margin: 8px;
font-size: 20px;
color: blue;
cursor: pointer;
>
b
text-decoration: underline;
>
button
cursor: pointer;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
p>
b>Click b> to change the span id="tag">html span>
p>
p>
to a span id="text">text span> node.
p>
p>
This button name="nada">button button> does nothing.
p>
script>
$( "p" ).on( "click", function( )
var htmlString = $( this ).html();
$( this ).text( htmlString );
>);
script>
body>
html>

Demo:

.html( htmlString ) Returns: jQuery

Description: Set the HTML contents of each element in the set of matched elements.

version added: 1.0 .html( htmlString )

version added: 1.4 .html( function )

A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

The .html() method is not available in XML documents.

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

Consider the following HTML:

div class="demo-container">
div class="demo-box">Demonstration Box div>
div>

The content of can be set like this:

$( "div.demo-container" )
.html( "

All new content. You bet!

"
);

That line of code will replace everything inside :

div class="demo-container">
p>All new content. em>You bet! em> p>
div>

As of jQuery 1.4, the .html() method allows the HTML content to be set by passing in a function.

$( "div.demo-container" ).html(function( )
var emphasis = "" + $( "p" ).length + " paragraphs!";
return "

All new content for " + emphasis + "

"
;
>);

Given a document with six paragraphs, this example will set the HTML of to

All new content for 6 paragraphs!

.

This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

To set the content of a element, which does not contain HTML, use the .text() method and not .html() .

Note: In Internet Explorer up to and including version 9, setting the text content of an HTML element may corrupt the text nodes of its children that are being removed from the document as a result of the operation. If you are keeping references to these DOM elements and need them to be unchanged, use .empty().html( string ) instead of .html(string) so that the elements are removed from the document before the new string is assigned to the element.

Examples:

Add some html to each div.

Источник

jQuery is a JavaScript framework that runs very fast with a very small size of JavaScript library code. It can easily implement a lot of JavaScript animation effects by operating DOM objects, processing events, and handling Ajax interactions. jQuery can simplify your JavaScript source code to improve your development speed and JavaScript code execution performance. In this article, I will tell you how to add jQuery links in both Html files and javascript files, and how to use jQuery to implement some basic animations with examples.

  1. The first thing you need to do is to download the jQuery library js file and add it into your Html file.
  2. Open a web browser and go to the jQuery library js file download page http://jquery.com/download/. Find the jQuery library js file download link, right-click it, in the popup menu list click Save Link As menu.
  3. The above action will save the jQuery library js file in a local folder, you can save it to any folder( for example your project lib folder).
  4. Next, you need to add the jQuery link in your Html page file like below source code. Below source code should be added in the head section of the target Html file.
  1. If you add the jQuery link in the Html source code, you must add the below code in every Html file head section. The disadvantage of this method is that if you want to use a new jQuery version you must update all Html files one by one manually, this is not a good method.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/OvyqoKL97Y0

2.1 Use document.writeln() Function To Add jQuery Link In JavaScript File.

  1. Add below js code in the include-jquery.js file, and then import the include-jquery.js file in test.html.
  2. include-jquery.js
// invoke javascript document object's writeln function to write 'import jquery lib js file string' in html page source code. document.writeln('');
/* Use $ to use jQuery object when the document load ready, then execute the anonymous funcion() */ $(document).ready(function() < // Register click event to all html a tag, the callback function will be triggered when user click a link in the html page. $('a').click(function(event) < // Prevent the link default behaviour, then click it will not open a target url. event.preventDefault(); // Popup an alert dialog. alert('The link will fade out.') // Fade out the link in the html page. $(this).hide("slow"); >); >);

2.2 Add jQuery By Create Script Element In Another JavaScript File.

// When the window load process complete then invoke load jquery lib js file function. window.load = load_jquery_lib_js_file(); function load_jquery_lib_js_file() < // Create a html script element. var script = document.createElement('script'); // Set the html script element's type to 'text/javascript'. script.type = 'text/javascript'; // Set the html script element's src attribute value to google online jquery lib js file. script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'; // When the jquery script load complete then invoke the handler function for different browsers. script.onreadystatechange = handler; script.onload = handler; // Append the html script element to the end of html page head section. document.getElementsByTagName('head')[0].appendChild(script); >// This function will be executed after jquery lib file has been loaded successfully. function handler()< // Write an message in browser console. console.log('jquery added :)'); // Create a html script element. var script = document.createElement('script'); // Set the html script element's type to 'text/javascript'. script.type = 'text/javascript'; // Set the html script element's src attribute value to the js file which will use jQuery object( it is use-jquery-when-jquery-is-loaded.js in this example ). script.src = './use-jquery-when-jquery-is-loaded.js'; // Append the html script element to the end of html page head section. document.getElementsByTagName('head')[0].appendChild(script); >
/* Use $ to use jQuery object when the document load ready, then execute the anonymous funcion() */ $(document).ready(function() < // Register click event to all html a tag, the callback function will be triggered when user click a link in the html page. $('a').click(function(event) < // Prevent the link default behaviour, then click it will not open a target url. event.preventDefault(); // Popup an alert dialog. alert('The link will fade out.') // Fade out the link in the html page. $(this).hide("slow"); >); >);

3. jQuery Example.

  1. This example contains two html files, hellow-world-alert.html and hello-world-add-number.html.

3.1 jQuery Hello World Alert Example.

  1. In the first example, it will display an alert dialog when the page is loaded.
  2. There is also a button with text “Welcome to JQuery world” in the page, when the button is clicked, it will show two alert dialog, the first alert dialog’s text is ‘You click the button’, the second alert dialog’s text is the button original text, then it will set button text to ‘Wish you like JQuery 🙂‘ and change the button’s text and background color.
  3. hello-world-alert.html
         

3.2 jQuery Hello World Add Number Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/u-x9_IQssaU

  1. This example uses jQuery to set the Html p tag css style. It also bind the mouse move event of the div tag, when your mouse moves in the div tag, the number will increase.
  2. hello-world-add-number.html
     -->    

Hello World From JQuery!

4.1 Question.

  1. I get some jQuery code from the internet, and it meets my requirements, so I want to add those jQuery codes to my Html page. I tried some methods, but failed, can anyone give me some help? Thanks a lot.

4.2 Answer1.

  1. You can create a new javascript file such as common-function.js and then paste your jQuery code into it.
  2. You can save this file in your js project home-directory/js folder. Then you can follow this article to add both the jQuery library js file and the common-function.js file into your Html page ( refer to sections 1, 2 at the beginning of this article ).
  3. And then you can use the jQuery code that you get from the internet. But you also need to make sure the web element id or name in the jQuery code matches the web element in your Html web page.

5. How To Use jQuery To Include Html File Content.

5.1 Question.

  1. My Html page (index.html) contains several other Html pages using the tag like below.

5.2 Answer1.

  1. You can use jQuery’s load() method to load the Html page content (menu.html, detail.html) into the DOM tree of the index.html page.
  2. Then the jQuery object that is created in the index.html page can access and manipulate the content of the menu.html, detail.html.
  3. Below is the example source code.

Источник

Оцените статью