简体   繁体   中英

Setting title attribute with Javascript function

I am trying to find, if I can pass a value on the title attribute of a label element using Javascript?

I have tried the following Javascript code:

function myFunction()
{
    return "Hello!";
}

And a piece of HTML code:

<label title="myFunction()">TEST</label>

But, this isn't working. It just show the 'myFunction()' as a text.

Is it possible, what I am trying to do? If yes, what is the correct syntax?

<label id='mylabel'>TEST</label>
<script>
    function myFunction() {
        return "Hello!";
    }

    document.getElementById('mylabel').setAttribute('title', myFunction());
</script>

Should do the job. It first selects the label and then sets the attribute.

You can't inline javascript like this.

What you may do is

1) give an id to your label and put this at the end of your body

<script>
   document.getElementById('myId').title = myFunction();
</script>

Demonstration

2) if you really want to inline the call, write this at the point where you want your label :

<script>
     document.write('<label title="'+myFunction()+'">TEST</label>');
</script>

(this is really not recommended)

Try this way:-

HTML:

<label id="lab">TEST</label>​

JS:

window.onload = function() {
    document.getElementById('lab').setAttribute('title','mytitle');
    alert(document.getElementById('lab').title);
}​

Refer LIVE DEMO

I got this! If you are using angular you can use this data Binding and call the function

<label title="{{myFunction()}}">TEST</label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM