23

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?

3
  • 3
    You cannot invoke a JS function from the title attribute. What is it you are trying to accomplish? Commented Oct 9, 2012 at 20:04
  • what are you trying to accomplish here? Commented Oct 9, 2012 at 20:07
  • Hi, I want a random number of labels that are in a template and get generated dynamically to also get dynamicaly using javascript the text to show. This text my differ it is not static Commented Oct 9, 2012 at 20:14

4 Answers 4

35
<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.

Sign up to request clarification or add additional context in comments.

2 Comments

OP wants to set the title using JavaScript, and my code does exactly that. What part of this answer do you think is wrong?
@KevinBoucher For me it was obvious, what OP is trying to do and daknøk's answer seems to fit perfectly here.
11

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)

3 Comments

What you describe should result in the same behavior as described by OP.
@KevinBoucher NO. See demonstration.
It is true that it would work, but please don't use document.write.
8

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

1 Comment

If i use jquery and have as a selector a certain class instead of the id then I can do to all the label required the text in the title that is needed. Your logic however is what I want to implement in general. Thanks
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.