Reputation: 11
I have a JSF application that produces a page with a label on it:
<label for="_idJsp0:question" class="left">Question</label>
And then elsewhere in the DOM is the component:
<td><textarea rows="7" cols="25" id="_idJsp0:question" name="_idJsp0:question">My Question.</textarea></td>
For Selenium, I am building a custom location strategy using jQuery, and so my question is how do return the ID of the label's "for" attribute? I can use .attr("for") on the label to return the string of the ID but I am missing how to actually return properly formatted selector output. I've tried approaches like:
var inner = "label:contains('Question')";
$('#' + $(document).find(inner).attr('for'));
Any help would be appreciated!
Upvotes: 1
Views: 3230
Reputation: 238078
This will print "My Question":
alert($("textarea[id='" +
$("label:contains('Question')").attr('for') +
"']").html());
It's looking for [id='xxx']
instead of #xxx
because there's a :
in the ID. But :
is a special character in jQuery selectors.
Upvotes: 0
Reputation: 25620
You need to escape the special jQuery selectors. Try something like this:
function jqescape(str) {
return str.replace(/[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\$&');
}
var inner = "label:contains('Question')";
$('#' + jqescape( $(document).find(inner).attr('for') ) );
Upvotes: 0
Reputation: 700212
It's the colon on the id that is keeping the selector from working. The text after the colon is interpreted as a meta-class instead of as a part of the id.
You have to escape the colon in the selector:
$('#' + $(document).find(inner).attr('for').replace(':', '\\:'))
For completeness; if you want to escape any special character in an identifier in a selector you would use a replace like this
id.replace(/([!"#$%&'\(\)\*\+,\.\/:;<=>\?@\[\\\]\^`\{\|\}~])/g, '\\$1')
Upvotes: 1