Setting title attribute with Javascript function

后端 未结 3 1189
逝去的感伤
逝去的感伤 2021-01-04 09:12

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 Javascrip

相关标签:
3条回答
  • 2021-01-04 09:13

    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)

    0 讨论(0)
  • 2021-01-04 09:13

    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

    0 讨论(0)
  • 2021-01-04 09:33
    <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.

    0 讨论(0)
提交回复
热议问题