how to enter a random value in a textarea without an id?

前端 未结 3 1914
花落未央
花落未央 2021-01-24 17:33

I have to enter a random value in a textarea of a web site by using grease monkey script the text area didn\'t have an id so document.getElementB

相关标签:
3条回答
  • 2021-01-24 17:59

    Use getElementsByName:

    document.getElementsByName("inpx_msg")[0]
    

    Obviously, you'll have to check if it exists, etc.

    0 讨论(0)
  • 2021-01-24 18:01

    It might be helpful to use getElementsByTagName:

    document.getElementsByTagName("textarea")[0]
    

    Of course, if you have more than one textarea tag, you will have to distinguish between them based on properties they might have. Or, if you know your textarea resides inside a specific element which has an ID, you could try

    document.getElementById("someparentid").getElementsByTagName("textarea")[0]
    
    0 讨论(0)
  • 2021-01-24 18:07

    You could use element.querySelector if you want to be able to specifically target an element using a CSS selector, similar to this:

    var textArea = document.querySelector('table tr td.pd5 textarea.msgbox');
    textArea.value = "My Random Text";
    

    The above is working on the following HTML example:

    <table>
        <tbody>
            <tr>
                <td class="tdv pd5"><span class="tbg">Message</span>&nbsp;</span>
                </td>
                <td class="pd5">
                    <textarea name="inpx_msg" class="msgbox"></textarea>
                    <br />
                    <div class="tsm">140 characters max.</div>
                </td>
            </tr>
        </tbody>
    </table>
    

    DEMO - Using element.querySelector


    Off course, you can now change the CSS selector to anything you like to match your DOM hierarchy. There is lots of flexibility using element.querySelector.

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