Javascript jQuery Sample Code to Add HTML Element to DOM Object
This Javascript tutorial demos a jQuery code sample to add HTML element to DOM object dynamically without posting to server. If you are a web developer or Javascript developer new to jQuery library, you can find the example useful. The jQuery sample code shows how to get reference to HTML objects, how to create events like click event and use of append method, etc.
Please check the following sample case. Just type into the textbox (input field) and press button to add the text into the message list as a seperate paragraph in the messages <div> DOM object.
First of all, within the <head> tag, add the jQuery javascript library reference:
As the second step, check the HTML code for input element (for message entry), button (firing jQuery code block) and the messages DIV object.
To manipulate the HTML DOM object using jQuery, by reading the input element value and modifying the target DIV object I used following Javascript code block.
You can add it to your HTML codes.
Let's read the above jQuery code for Javascript developer and walk through the script
First of all, when the HTML document is loaded completely I can execute my code by using a function (without a name defined) which appends two events "click" and "mouseenter" events.
Click event is attached to all elements with "button" tag.
And the "mouseenter" event is attached to HTML element with "input" tag with the "name" attribute is "yourmessage"
The Javascript mouseenter event, clears the input element when the web user moves the mouse onto the HTML element.
The jQuery code $("input[name=yourmessage]") enables the developer to get the DOM reference of the input element.
Then using .val("") method with empty string, the value of the input text element is cleared.
Let's read the .click event code now.
Using the jQuery code, we create a javascript variable and store the input element text value.
Then we get the messages DIV object reference using jQuery code $('#messages')
Then we append the HTML code - (or object) that surrounds the stored text with "p" tags - to the messages DIV
Let's try and see how the jQuery example code works: