To manipulate the title attribute, you can use the standard attr() method. Using this method, you can read the current value of the title attribute, or you can write a new value.

Read title attribute

<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(titleFunc);
function titleFunc() {
  // Find the element #mydiv, read the contents of the title attribute and save it to the variable myTitle
  var myTitle = $('#mydiv').attr("title");
 
  // Print the variable myTitle in the tag with id='result'
  $('#result').html(myTitle);
}
</script>
</head>
<body>
  <div title="old title" id="mydiv">
  </div>
   
  <!-- Variable output tag myTitle -->
  <div id="result">
  </div>
</body>
</html>

   Transfer this code to the browser and check that everything works correctly. The resulting code should be:

<div title="old title" id="mydiv"></div>
<div id="result">old title</div>

   In order to consolidate the material, I propose to add another element with the title, read it and display it on the screen.

Writing attribute title

   Writing to the title attribute is as simple as reading the value. In the attr() method, not one argument will be used, but two. The first argument is the attribute, and the second is the attribute.

attr (attributeName, value)

<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(titleFunc);
function titleFunc() {
  // Find the element #mydiv, replace the content of the title attribute with 'NEW title'
  $('#mydiv').attr("title", "NEW title");
   
  // The value of the title attribute is entered into the myTitle variable.
  var myTitle = $('#mydiv').attr("title");
   
  // Print the variable myTitle in the tag with id = 'result'
  $('#result').html(myTitle);
}
</script>
</head>
<body>
  <div title="old title" id="mydiv">
  </div>
   
  <!-- Variable output tag myTitle -->
  <div id="result">
  </div>
</body>
</html>

   As a result of the implementation we get:

<div title="NEW title" id="mydiv"></div>
<div id="result">NEW title</div>

   And that’s not a big test:

1. What happens when you type $(‘#mydiv’).attr(«title», «NEW title»); ?

 
 
 
 

2. What do the attr() method arguments mean in the following expression $(‘#mydiv’).attr(attributeName, value);  ?

 
 
 
 

3. What we get as a result of the command $(‘#mydiv’).attr(«title»); ?

 
 
 
 

Question 1 of 3

   Now on working with the title attribute you are a Guru!