VBA getElementById not working [duplicate] - vba

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
document.getElementById('id of div that definately exists') returns null.
I originally loaded the javascript last in order to make sure I wouldn't need to worry about the onload event. I also tried using the onload event. It's very spooky. Any ideas or help would be greatly appreciated.

Also be careful how you execute the js on the page. For example if you do something like this:
(function(window, document, undefined){
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
This will return null because you'd be calling the document before it was loaded.
Better option..
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);

It can be caused by:
Invalid HTML syntax (some tag is not closed or similar error)
Duplicate IDs - there are two HTML DOM elements with the same ID
Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?
Please, post your code.

There could be many reason why document.getElementById doesn't work
You have an invalid ID
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
(resource: What are valid values for the id attribute in HTML?)
you used some id that you already used as <meta> name in your header (e.g. copyright, author... ) it looks weird but happened to me: if your 're using IE take a look at
(resource: http://www.phpied.com/getelementbyid-description-in-ie/)
you're targeting an element inside a frame or iframe. In this case if the iframe loads a page within the same domain of the parent you should target the contentdocument before looking for the element
(resource: Calling a specific id inside a frame)
you're simply looking to an element when the node is not effectively loaded in the DOM, or maybe it's a simple misspelling
I doubt you used same ID twice or more: in that case document.getElementById should return at least the first element

Related

Storing and reusing the text content of an object using Playwright and Javascript, then use it for assertion/validaton

I would like to store the text from an object locator and use it for assertion. For instance, I have a trade number - 1234. This trade number only appears after a transaction, so it is not static on other screens. This number is located on several other screens and I need to validate that it appears. I am able to locate the element through inspect and Playwright accepts it, but having issues:
Grabbing the text (1234)
Then setting up an assertion statement to compare it
Below are my humble and naïve attempts:
async getConfirmNumber() {
//Store the contents in the page locator which has the trade number
const tradeNumber = page.locator('div:nth-of-type(2) > .col-md-9.display-value.ng-binding').textContent;
//Navigate to a different screen which now will display the trade number
await this.page.click('a[caption="History"]')
await this.page.click('a[href="#/trade-summary"]')
//Line of code that I am not sure how to correctly write. ".bidconfirmation" is the locator on the new screen which displays the trade number.
//If the contents or value of ".bidconfirmation" is NOT 1234 then an error needs to display.
await expect(tradeNumber).toHaveCSS('.bidconfirmation', tradeNumber);
}
Just to let you know I would change the tag on this post to playwright-JavaScript to better reach the intended audience.
However, if I understand your question correctly you are trying to get the text content of an element but the textContent() method is not working, I would try to use the innerText() method and see if that works.
Apologies if this is a little off as I work with the java version of Playwright but you could do:
const tradeNumber = page.locator('div:nth-of-type(2) > .col-md-9.display-value.ng-binding').innerText(); //BTW I would change this locator to something unique or a little more stable -- this should give you the tradeNumber
//then I'm not 100% sure what your trying to do here but if I understand correctly this might help
await expect(page.locator('.bidconfirmation').toHaveValue(tradeNumber));
I hope this helped a little, Im sorry I couldn't really get an understanding fully of the question you were asking but feel free to take a look at playwright.dev to find documentation surrounding Playwright.

iMacros Tag Line properties

I'm trying to create a macro to log in to a company owned web page. When I record putting the cursor into the User Name text box, the following command is recorded:
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:/pdp/qnyfy/resumeSAML50/pdp/startSSO.ping
The problem is that the "qnyfy" part of the tag line changes. The next time I try to record this tag line, every thing is the same except that "qnyfy" changes to something else; which renders my VBA code useless for logging into this web page.
Is there a way to extract this information first, find out what that 5 characters should be and then re-build a string to use the correct tag line?
Windows 7
Excel 2016
iMacros 10.3
Thanks for the help........
OK, #OP opened some parallel Thread on the iMacros Forum (iMacros Tag Line Properties), which allows me to simplify a bit this Answer and to remove a few of the original IF-IF-IF...
(The parallel Thread contains a bit more (Background) Info and more precise Sols/Scripts applied to this specific Script, for those interested...)
First, FCI (Full Config Info) was originally not completely clear, now it is:
=> iMB v10.3, 'Scripting Interface' v10.3, Win7.
("iMacros v10.3" could have meant 'v10.3 for CR 'Free'/'PE'' also...)
(The 'TAG' Statement is truncated is this Thread, it is complete + complete Script in the parallel Thread...)
Several Solutions, I'll go from "simplest" to "more complex":
1- The 'FORM' Parameter can probably simply completely be removed. It is usually not needed, unless there are several Forms on the Page with similar HTML Elements, here the 'INPUT' Field.
2- Same like '1', but using for example the 'CLASS' Attribute or any Attr(s) that might identify this 'INPUT' Field uniquely if there are several Forms on the Page with similar (but not identical) 'INPUT' Fields. (Or by adjusting the 'POS=n' if they are identical...)
3- Same like '1' or '2', but combined with 'Relative Positioning', on some HTML Element that can be identified "easily" and uniquely to be used as the Anchor, either inside ('3a') the same 'FORM' or 'DIV' (=> this 'INPUT' probably has some 'Label' next to it like some "Login:" for example), or just outside ('3b') if that Form has some Name/Title for that "Section", usually in 'H2' or 'H3' Type.
4- Simply replace the dynamic part ("qnyfy") with a Wildcard:
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:/pdp/*/resumeSAML50/pdp/startSSO.ping
Sols [1-4] probably provide a "Shortcut" to probably achieve the desired Result, but they actually don't really answer #OP's Qt which was "How to identify/extract/isolate this "qnyfy" 5 Letter String...?"
5- Using first one of [1-4] Methods, manage to tag some Element that will be inside that 'FORM', either the 'INPUT' Field itself or one Element that could be used as Anchor in '3a' (with Anchor Inside the Form), and then use 'Double Relative Positioning' (more Info on the iMacros Forum where I've several times already completely explained the Principle) to identify and tag and extract (=HTM) the complete 'Containing 'DIV'' (or could be 'SPAN', but there will very probably be some (outer) 'DIV' also) containing the 'FORM' to then isolate the "qnyfy" part using 'EVAL', stg like...:
SET !EXTRACT_TEST_POPUP NO
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:/pdp/*/resumeSAML50/pdp/startSSO.ping ATTR=CLASS:* EXTRACT=TXT
TAG POS=R-1 TYPE=DIV ATTR=TXT:* EXTRACT=TXT
SET !EXTRACT NULL
TAG POS=R1 TYPE=DIV ATTR=TXT:*&&CLASS:* EXTRACT=HTM
SET Form_ID EVAL("var s='{{!EXTRACT}}'; var x,y,z; x=s.split('ACTION:/pdp/'); y=x[1].split('/'); z=y[0]; z;")
PROMPT EXTRACT:<BR><BR>{{!EXTRACT}}<BR><BR>Form_ID:<SP>_{{Form_ID}}_
6- This one actually comes between '4' and '5', it would be by using '3b' to first locate some Anchor outside the 'FORM' and its 'Containing 'DIV'', then only one Level of 'Relative Positioning' would be needed... (And the 'EVAL()' Statement remains the same...)
That's it...! It would help / add some "Reliability" if for example the Class of the Containing 'DIV' can be identified/added.
Not relevant for iMB v10.3 anymore:
And if "iMacros v10.3" meant "iMacros for CR v10.3 'Free'", you'll need to use ['!VAR1'-'!VAR3'] instead of 'Form_ID' as User Defined Vars are not supported in the 'Free' Version...
[All Solutions/Scripts not tested of course...! Hum, I had previously mentioned that I could directly think of 3 or 4 Solutions, here are already 6, ah-ah...!, and there are also different possible Variants on all 6 of them...]
7- In the parallel Thread on the iMacros Forum, I also mentioned and explained about a Sol_7 using the 'EVENT' Mode with or without ID, which wouldn't be of use for this User as the 'EVENT' Mode was not supported in iMB v10.3.
Rmk:
Sol_5 and Sol_6 can actually be used to deal with Dynamic ID's, same Principle...!
>
I might one day have to delete this Answer as I am currently (re)using each time my last 5/5 'Answer_Credit', I each time have to delete some previous Answer, to be able to post a 5th one, as most Users on the 'iMacros' Tag-Channel usually never follow up on their Threads and don't do "+1" or "Accept Solution"..., and all my previous Answers also usually all get downvoted anyway by some "angry" User(s), so I never manage to pass the Threshold for more than 5 Answers, ah-ah...!, tja...!
(No big deal probably as I actually never or very-very rarely answer Threads on SOF as I don't like the Rep-Pts System, I only answered this one because #OP is a "nice User" that I knew from the iMacros Forum, ah-ah...!)
(I still don't know what the 'community wiki' CB means below posting an Answer...?)

Selenium Webdriver - using isDisplayed() in If statement is not working

I am creating a script that involved searching for a record and then updating the record. On the search screen, the user has the option of viewing advanced search options. To toggle showing or hiding advanced search is controlled by one button.
<a title="Searches" href="javascript:expandFilters()"><img border="0" align="absmiddle" alt="Advanced" src="****MASKED URL****"></a>
The only difference between the properties of the search button when it is showing or hiding the advanced search is the img src:
When advanced search is hidden the IMG src ends with "/Styles/_Images/advanced_button.jpg", when advanced search is visible, the IMG src ends with "/Styles/_Images/basic_button.png"
When I open the page, sometimes the Advanced search options are showing, sometimes they aren't. The value that I want to search on appears in the Advanced section, so for my script to work I have added an IF statement.
<input type="text" value="" maxlength="30" size="30" name="guiSystemID">
The IF statement looks for the fields that I need to enter data into, and if the field does not exist then that would indicate that the Advanced options are not visible I need to click on the button to expand the search option.
I created the following IF statement.
if (!driver.findElement(By.name("guiSystemID")).isDisplayed()) {
driver.findElement(By.cssSelector("img[alt='Advanced']")).click();
}
When I run the script and the Advanced search is expanded then the script runs successfully. However, when I run the script and the Advanced search is not expanded, the script fails, advising me that it could not find the object "guiSystemID". This is frustrating because if it can't find it then I want the script to continue, entering into the True path of the IF statement.
Has anyone got any suggestions about how else I could assess if the field is appearing without having the script fail because it can't find the field.
Thanks in advance
Simon
I might be late in answering this, but it might help someone else looking for the same.
I recently faced a similar problem while working with isDisplayed(). My code was something like this
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**Do this*/
}
else
{
/**Do this*/
}
This code works pretty well when the element that isDisplayed is trying to find is present. But when the element is absent, it continues looking for that and hence throws an exception "NosuchElementFound". So there was no way that I could test the else part.
I figured out a way to work with this(Surround the {if, else} with try and catch block, say something like this.
public void deleteSubVar() throws Exception
{
try
{
if(driver.findElement(By.xpath(noRecordId)).isDisplayed() )
{
/**when the element is found do this*/
}
}
catch(Exception e)
{
/**include the else part here*/
}
}
Hope this helps :)
I've had mixed results with .isDisplayed() in the past. Since there are various methods to hide an element on the DOM, I think it boils down to a flexibility issue with isDisplayed(). I tend to come up with my own solutions to this. I'll share a couple things I do, then make a recommendation for your scenario.
Unless I have something very specific, I tend to use a wrapper method that performs a number of checks for visibility. Here's the concept, I'll leave the actual implementation approach to you. For general examples here, just assume "locator" is your chosen method of location (CSS, XPath, Name, ID, etc).
The first, and easiest check to make is to see if the element is even present on the DOM. If it's not present, it certainly isn't visible.
boolean isPresent = driver.findElements(locator).size() > 0;
Then, if that returns true, I'll check the dimensions of the element:
Dimension d = driver.findElement(locator).getSize();
boolean isVisible = (d.getHeight() > 0 && d.getWidth() > 0);
Now, dimensions, at times, can return a false positive if the element does in fact have height and width greater than zero, but, for example, another element covers the target element, making it appear hidden on the page (at least, I've encountered this a few times in the past). So, as a final check (if the dimension check returns true), I look at the style attribute of the element (if one has been defined) and set the value of a boolean accordingly:
String elementStyle = driver.findElement(locator).getAttribute("style");
boolean isVisible = !(elementStyle.equals("display: none;") || elementStyle.equals("visibility: hidden;"));
These work for a majority of element visibility scenarios I encounter, but there are times where your front end dev does something different that needs to be handled on it's own.
An easy scenario is when there's a CSS class that defines element visibility. It could be named anything, so let's assume "hidden" to be what we need to look for. In this case, a simple check of the 'class' attribute should yield suitable results (if any of the above approaches fail to do so):
boolean isHidden = driver.findElement(locator).getAttribute("class").contains("hidden");
Now, for your particular situation, based on the information you've given above, I'd recommend setting a boolean value based on evaluation of the "src" attribute. This would be a similar approach to the CSS class check just above, but used in a slightly different context, since we know exactly what attribute changes between the two states. Note that this would only work in this fashion if there are two states of the element (Advanced and Basic, as you've noted). If there are more states, I'd look into setting an enum value or something of the like. So, assuming the element represents either Advanced or Basic:
boolean isAdvanced = driver.findElement(locator).getAttribute("src").contains("advanced_button.jpg");
From any of these approaches, once you have your boolean value, you can begin your if/then logic accordingly.
My apologies for being long winded with this, but hopefully it helps get you on the right path.
Use of Try Catch defies the very purpose of isdisplayed() used as If condition, one can write below code without using "if"
try{
driver.findElement(By.xpath(noRecordId)).isDisplayed();
//Put then statements here
}
Catch(Exception e)
{//put else statement here.}

mvc4 jquery autocomplete items showing up as asterisks instead of readable data

I got my autocomplete stuff working well enough to see that it's returning some data when I type in a field--but the data shown in the dropdown below the textbox is just a vertical column of asterisks or list item bullets. (I can't really tell what they are.)
When I query the web service directly in the browser, it returns a Json array as expected which looks like this where, for example ?term=chi (I've added some line breaks for readability)
[
{"Name":"Chihuahua"},
{"Name":"Chinese Crested"},
{"Name":"Chinese Shar-Pei"},
{"Name":"Japanese Chin"},
{"Name":"Schipperke"}
]
My JavaScript looks like this:
$(function() {
$("#Breed").autocomplete({
source: "#Url.Action("BreedList", "Patient")"
});
});
like I say, my textbox in question (#Breed) does respond sort of like an autocomplete box, but the dropdown data is weird. Any ideas?
Although I did have a CSS bundling problem (somehow I had omitted the jquery ui css from my bundle), a bigger issue was that the Json returned by my service needed a lower case "value" property for each item. I was using the column name as cased on my Linq query. The tip that pointed me in the right direction on this came from the answer here: jQueryUI autoComplete returns back empty list

selenium getXpathCount

HI there
selenium.getXpathCount does not find element, any one hoas any idea ? Here is my code:
if (existArtist){
int result = selenium.getXpathCount("//*[#id='chugger-results']/div[1]/ul/li").intValue();
if (result>0){
//DO THIS
Either you have a broken DOM (Do a W3C Validation and see if you have any unclosed tags) or your XPath is looking for an element that doesn't exist.
We would need to see the entire HTML of the page to be able to answer your question (more visibility of your test code would be useful too)