Changing Html Content and Attributes with Jquery

Changing the Content and Properties of Html Objects

Thanks to the HTML DOM interface, the contents and properties of HTML objects can be accessed and changed using languages ​​such as JavaScript. The following methods can be used to obtain and change the content of HTML elements:

text: Allows to get or change the text in the specified object. HTML codes inside the tag are skipped and only plain text is obtained. (See the examples section.)

html: Allows to obtain or change the content of the specified object in html.

val: It is used to obtain and change the value in form elements, for example a text box. The attr method is used to obtain and change the properties (parameter values) of HTML tags.

Changing the Text in Html Tags with the Text() Method

As you will see in the examples section, the text method is used to obtain the plain text inside an HTML element.

To get the text inside the HTML tag;


$("#text1").text();

To change:

$("#text2").text(“text to add”);

For example, let's put the text inside the h1 tag into a variable:

var a = $("h1 ").text();

Now let's change the text in the label whose id is box1 to "Hi":

$("#box1").text(“Hi”);

The example below writes the text in the text1 element to the text2 element. (A working version is available in the examples section.)

$("#button1").click(function(){

 var firstParagraph = $("#text1").text();

 $("#text2").text(firstParagraph);

});

Changing the Content of Html Tags with the JQuery Html() Method

The html method allows us to obtain or change the content of an element, including the html tags it contains. To get the content of the HTML tag;


$("#text1").html();

To change:

$("#text2"). html (“content to add”)

For example, let's put the entire content of the article tag into a variable:

var content = $("article "). html();

Now let's change the content of the label whose id is box1 to "Hello":

$("#box1").html(“Hi”);

The example below writes the text in the text1 element to the text2 element. (A working version is available in the examples section.)

$("#button1").click(function(){

 var firstParagraph = $("#text1"). html();

 $("#text2"). html (firstParagraph);

});

Obtaining and Changing the Value of a Form Element

The val() method is used to obtain the value in HTML form elements. For example, to obtain the value of a text box whose id is box1;


var number = $("#box1").val();

To change:

$("#box1").val(number);

$("#box1").val(“Hi”);

$("#box1").val(123);

Examples such as: