Skip to main content

Set Content and Attributes

In this tutorial, we will delve into the 'Set Content and Attributes' aspect of jQuery HTML/CSS Manipulation. jQuery provides us with a powerful set of tools to manipulate the content and attributes of our HTML elements dynamically. We'll cover the key methods jQuery offers for these tasks, namely .html(), .text(), .val(), and .attr().

Setting Content

.html()

The .html() method in jQuery is used to set or return the content of selected elements, including HTML markup.

For example, consider the following HTML code:

<div id="example">This is an example.</div>

You can use the .html() method to get the content of the div:

var content = $("#example").html();

The variable content now holds the string "This is an example".

Similarly, you can set the content of the div using .html():

$("#example").html("<b>New content</b>");

Now, the div content is "New content", wrapped in bold tags.

.text()

The .text() method is similar to .html(), but it's used to set or return the text content of selected elements, excluding HTML markup.

Using the same div as before, you can get the text content as follows:

var content = $("#example").text();

To set the text content, you can use:

$("#example").text("New content");

Now, the div content is "New content", without any bold tags.

.val()

The .val() method is used to set or return the value of form fields.

Consider an input field:

<input type="text" id="name" value="John Doe">

You can get the value of this input field like this:

var name = $("#name").val();

To set the value, you can use:

$("#name").val("Jane Doe");

Now, the value of the input field is "Jane Doe".

Setting Attributes

.attr()

The .attr() method in jQuery is used to set or return the value of an attribute.

Consider a link:

<a href="https://example.com" id="link">Visit example.com</a>

You can get the href attribute of this link as follows:

var link = $("#link").attr("href");

To set the href attribute, you can use:

$("#link").attr("href", "https://new.example.com");

Now, the href attribute of the link is "https://new.example.com".

These are the basics of setting content and attributes using jQuery. Practice these methods, and you'll soon be able to manipulate your HTML elements with ease. Remember, the key to mastering jQuery is consistent practice and exploration. Happy learning!