add title attribute from css

How to add title='mandatory' from css to the following

     <label class='mandatory'>Name</label>

.mandatory
{
background-image:url(/media/img/required.gif);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
font-weight:bold;
}

Well, although it's not actually possible to change the title attribute, it is possible to show a tooltip completely from CSS. You can check a working version out at http://jsfiddle.net/HzH3Z/5/.

What you can do is style the label:after selector and give it display:none, and set its content from CSS. You can then change the display attribute to display:block on label:hover:after, and it will show. Like this:

label::after {
  content: "my tooltip";
  padding: 2px;
  display: none;
  position: relative;
  top: -20px;
  right: -30px;
  width: 150px;
  text-align: center;
  background-color: #fef4c5;
  border: 1px solid #d4b943;
  -moz-border-radius: 2px;
  -webkit-border-radius: 2px;
  -ms-border-radius: 2px;
  border-radius: 2px;
}
label:hover::after {
  display: block;
}

You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before and :after).


Quentin is correct, it can't be done with CSS. If you want to add a title attribute, you can do it with JavaScript. Here's an example using jQuery:

$('label').attr('title','mandatory');

Can do, with jQuery:

$(document).ready(function() {
    $('.mandatory').each(function() {
        $(this).attr('title', $(this).attr('class'));
    });
});

As Quentin and other suggested this cannot totally be done with css(partially done with content attribute of css). Instead you should use javascript/jQuery to achieve this,

JS:

document.getElementsByClassName("mandatory")[0].title = "mandatory";

or using jQuery:

$('.mandatory').attr('title','mandatory');

document.getElementsByClassName('mandatory')[0].setAttribute('title', 'mandatory');

$('.jmandatory').attr('title', 'jmandatory');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Place the Mouse Over the following elements to see the title,
<br/><br/>
<b><label class="mandatory">->Javascript Mandatory</label></b>
<br/><br/>
<b><label class="jmandatory">->jQuery Mandatory</label></b>