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

别说谁变了你拦得住时间么 提交于 2019-12-31 05:12:20

问题


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.getElementById doesn't work.

Can I use another method to do that?

My current HTML showing my textarea:

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

回答1:


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.




回答2:


Use getElementsByName:

document.getElementsByName("inpx_msg")[0]

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




回答3:


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]


来源:https://stackoverflow.com/questions/15596953/how-to-enter-a-random-value-in-a-textarea-without-an-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!