Does anyone know how to delete an element from the source using Watir? There doesn't seem to be a method for removing elements. Perhaps I'm missing something.
-
2I don't think this is part of the functionality of Watir. Can I ask what you're trying to achieve by deleting an element from the source? Someone might be able to suggest another gem that can better assist you in what you're trying to do. – anonygoose Oct 29 '11 at 18:53
-
2@anonygoose is correct. Watir is meant for running tests. Could you be more specific about deleting from source? You want to save the source and edit it locally ? Perhaps take a look at the Nokogiri and Mechanize gems. – Kassym Dorsel Oct 29 '11 at 21:27
4 Answers
If you know JavaScript, you could execute any JavaScript code on the page.
Example:
browser.execute_script("some javascript code")
I am not a JavaScript ninja, but this question could help you: JavaScript: remove element by id.

- 1
- 1

- 56,372
- 28
- 94
- 125
Remove elements by css:
browser.execute_script("[...document.querySelectorAll('.some.class')].map(e => {e.parentNode.removeChild(e)})")

- 53,827
- 19
- 119
- 159
We can remove it with javascript. Here's an example to remove a breadcrumbs div element but it's id:
browser.execute_script("bd = document.getElementById('breadcrumbs'); bd.parentNode.removeChild(bd);")

- 5,780
- 3
- 19
- 21
The Purpose for Watir is to do web testing, which is to say drive the browser as if a user was interacting with it. That means doing the things a user could do, clicking on stuff, filling in input fields, etc. It also means being able to verify what is there on the screen that the user can see or interact with.
Since a user cannot delete elements, there is no means by which to do that using the tool.
If the application provides a way for users to 'remove' or 'delete' something, like closing a simulated window, removing a tab etc, then you need to do that by simulating what the user would do (usually clicking on some specific element) in order for that to happen.

- 6,660
- 2
- 28
- 43
-
I think Capybara is more of a testing framework and Watir is more of a scraping tool. YMMV though, everyone has different needs. Also, as a (somewhat advanced) user. I delete elements all the time from the console. – pguardiario Jul 31 '18 at 09:51
-
Watir stands for Web Application Testing In Ruby.. it's most definitely designed as a testing tool, NOT a scraping tool. Been that way throughout all it's history http://watir.com/history/. Yes, you can do lots of things from the console.. but that's a developer tool, not something 98% of browser users have ever touched – Chuck van der Linden Aug 28 '18 at 19:31