What is the difference between getText() and getAttribute() in Selenium WebDriver? - java

Both are used to get the WebElement value in between tags.
Is my assumption right? If wrong, please elaborate.

<input attr1='a' attr2='b' attr3='c'>foo</input>
getAttribute(attr1) you get 'a'
getAttribute(attr2) you get 'b'
getAttribute(attr3) you get 'c'
getText() with no parameter you can only get 'foo'

getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like
<input name="Name Locator" value="selenium">Hello</input>
Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".
Returns:
The attribute's current value or null if the value is not set.
driver.findElement(By.name("Name Locator")).getAttribute("value") //
The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.
getText() -> delivers the innerText of a WebElement.
Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
driver.findElement(By.name("Name Locator")).getText();
'Hello' will appear

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
In above html tag we have different attributes like src, alt, width and height.
If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute() method
Syntax:
getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104

getText(): Get the visible (i.e. not hidden by CSS) innerText of this
element, including sub-elements, without any leading or trailing
whitespace.
getAttribute(String attrName): Get the value of a the given attribute of the element.
Will return the current value, even if this has been modified after
the page has been loaded. More exactly, this method will return the
value of the given attribute, unless that attribute is not present, in
which case the value of the property with the same name is returned
(for example for the "value" property of a textarea element). If
neither value is set, null is returned. The "style" attribute is
converted as best can be to a text representation with a trailing
semi-colon. The following are deemed to be "boolean" attributes, and
will return either "true" or null: async, autofocus, autoplay,
checked, compact, complete, controls, declare, defaultchecked,
defaultselected, defer, disabled, draggable, ended, formnovalidate,
hidden, indeterminate, iscontenteditable, ismap, itemscope, loop,
multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
paused, pubdate, readonly, required, reversed, scoped, seamless,
seeking, selected, spellcheck, truespeed, willvalidate Finally, the
following commonly mis-capitalized attribute/property names are
evaluated as expected: "class" "readonly"
getText() return the visible text of the element.
getAttribute(String attrName) returns the value of the attribute passed as parameter.

Related

Set a dynamic value for the "disabled" parameter of the struts radio

so i am tring to create a struts radio that will show elements (throught a list passed into the parameters "list" and "listKey".
What i am trying to add to that is that some radios will be read-only (based on some field declared on a server-side bean).
So struts radio is like this in the jsp :
<s:radio id="radioStatutType"
name="radioStatutType"
theme="extend"
templateDir="template"
list="statList"
listKey="myId"
listValue="label"
onclick="checkType();"
disabled="disabRgt" />
So the fields "myId" and "label" are declared in the same bean and they both work perfectly (so the scope is correct i think).
Same as these two fields, i declared a String named "disabRgt" (in the bean) that is filled with true/false (with a toString on a boolean calculated with some code). I declared the setter and getter but when displaying the jsp (and the radio) this field is not used (i verified throught debug watchpoint access/modification).
So i changed this field into boolean (primitive) and it did not work. Finally, i changed the getter into "isDisabRgt" instead of "getDisabRgt" => Same result ..
So it seems that the field "disabRgt" is never evaluated and that the "disabled" parameter in the radio is always filled with the default value (which is false).
Hope i explained it well ! Any ideas ?
Since disabled="%{myBoolean}" doesn't evaluate the expression, you must do it in some other way:
Using <s:if> on the variable to display the radio enabled or disabled:
<s:if test="%{disabRgt}">
<s:radio ... disabled="true" >
</s:if>
<s:else>
<s:radio ... >
</s:else>
Disabling it with Javascript:
<script>
$(function() {
if (<s:property value="%{disabRgt}"/>){
$("#radioStatutType").prop( "disabled", true );
}
});
</script>
Just remember to always use booleans, never voodoos like Boolean's toString()s ;)

Set the value for an hidden form element

i am using HTMLUNit to set the value of a form hidden element as below.
HtmlHiddenInput hidden = (HtmlHiddenInput) page.get("someid");
hidden.setValueAttribute(seriesName);
But this does not work as expected and throw an castException.
I have div element like follows
<div class="myclass">
<form:hidden id="someid" htmlEscape="true"/>
</div>
How can i set the value for that hidden form id using HTMLUNIT.
Thanks.
You don't need to use HtmlHiddenInput. If you are getting a cast exception, use a base object, as DomElement.
DomElement myInput = page.getElementById("someid");
myInput.setAttribute("value", seriesName);
So with any html dom element, the value attribute will be set to seriesName

javascript document.forms[0] and document.<formname> have different elements

I am trying to implement client side validation in Struts 2. my theme is xhtml. The javascript generated is not able to validate my code. After debugging , I found that Struts is using the following notation to refer the elements.
form = document.getElementById(<form id>);
service = form.elements['service'];
the point is that service is coming as undefined.
when I checked that form.elements is null; However if I access form using document.formname i am able to see the fields in elements collection.
I am thinking document.forms[0] is returning the same object as document.getElementById(formid). What is the difference?
The form element can access fields by name, for this purpose you should get the form element. You can do it in many ways, use document.getElementById() or document.forms[], or $("#formid"). Whatever way you choose doesn't matter. Just note that a document can contain many forms, so you should reference a correct one. Getting form element by id returns an element that has an id attribute, getting it by the index in the forms property you should know the correct index. Once you get the form element you can reference input fields by name. For example
<form id="formid">
<input name="service">
</form>
<script>
var v = document.getElementById("formid")['service'];
</script>

constructing URL with struts 2 param tag if param vaue is null/empty?

I'm making below url through Struts 2 tag. The problem is if there is no attribute 'cust_key' in request, url does not append ?custKey_key= to the url.
var custUrl= '<s:url namespace="/customer" action="view-customer" method="viewCustomer" escapeAmp="false"/> <s:param name="custKey_key" value="#request['cust_key']" /> </s:url>';
Is there a attribute in s:param tag where specified param is always appended even if value is empty or null?
From JavaDocs of this custom tag (please see inherited addParameter method):
... If the provided value is null any existing parameter with the given
key name is removed...
So you need to pass some value, you could try at least empty string.

how to add an attribute to an XML element

I am using the DOM parser. I have to parse the following XML:
<abc>
<type action="">
<code>test</code>
<value>001</value>
</type>
<type action="">
<code>test2</code>
<value>002</value>
</type>
</abc>
so, depending on the value field under the type field, I have to fill in the action attribute in the type field. I am a bit stumped. I am able to get the value of the value field, but I don't know how to go back and add the attribute.
Any help will be appreciated a lot!!!
thanks!
To go back, just save a reference to the type Element before you traverse to its value child. (assuming you visited it already).
to change the value, use the setAttribute() method.
edit:
Alternate method: from the value text node, call getParentNode() twice (once to get back to the value element & once to get back to the type element), then call setAttribute() after you do any necissary casting.
try something like
nodelist = doc.getElementsByTagName("value");
for (Element element : nodelist) {
Element parent = element.getParentNode()
parent.setAttribute("action", "attrValue");
}

Categories

Resources