Using Javascript/jQuery to access HTML elements wi

2020-04-28 09:00发布

I'm making a Greasemonkey script for someone to change the display of some of the fields their CRM(Zoho) created because they don't have access to change the rendered HTML.

This should be easy, BUT Zoho decided that creating proper HTML was too big a pain in the ass, I guess, and their HTML contains things like this:

<input type="text" maxlength="50" style="width: 100%;" class="textField" id="property(Phone)" name="property(Phone)"/>

The ID's contain spaces and parentheses, which aren't valid in ID attributes, and is preventing me from using either document.getElementById() to select them or from using jQuery to select them.

Does anyone have any ideas for how I could grab that element? Obviously I could grab it via its index in its parent element, or by traversing the DOM, but both of those would mean that if the order of the fields changed, the Greasemonkey script would stop working correctly because it would then be targeting the wrong elements.

5条回答
迷人小祖宗
2楼-- · 2020-04-28 09:30

You can escape the brackets like this:

$("#property\\(Phone\\)")
查看更多
混吃等死
3楼-- · 2020-04-28 09:36

You could always do a document.getElementsByTagName('input'), then browse the results and match it with it's attributes (like it's type and name, class...). Not very efficient but the only way I know that will work with any order (since the id is invalid)...

var inputs = document.getElementsByTagName('input');
if (inputs)
    for (var i = 0; i < inputs.length; i++)
        if (inputs[i].type == 'text' && inputs[i].name == 'SearchValue')
            return inputs[i];

I'm pretty sure JQuery (or any other good framework) have an equivalent to this snippet...

查看更多
冷血范
4楼-- · 2020-04-28 09:42

You can escape the spaces and parentheses using backslashes:

$('#property\\(Phone\\)').val('jQuery selected property(Phone)!');
$('#ab\\ cd\\ ef').val('jQuery selected ab cd ef!');
查看更多
够拽才男人
5楼-- · 2020-04-28 09:49

What browser is this for? Firefox, I assume, since you mention GreaseMonkey. But document.getElementById("property(Phone)") seems to work just fine in Firefox 3.5.

查看更多
叛逆
6楼-- · 2020-04-28 09:52

JQuery probably can't find it using #id syntax, but could probably find it using tagName[id=value] syntax... try it, and good luck. See the jQuery doc.

查看更多
登录 后发表回答