New project.
Main form size around 670, 420
Add a button on the top-left of the form, text: Change
Add a button to the right of the previous one, text: Active
Add a webbrowser to the form below the button, size 615, 230, anchor: Top, Bottom, Left, Right
Below the webbrowser, add a textbox, multiline: yes, size: 615, 50, anchor: Bottom, Left, Right, scrollbars: Vertical
If you have done example 24 then you can use the same html file for this example too. Otherwise, open notepad, insert the html code present on the bottom of the Visual Basic 24 post, and save as "Elements.html" to your hard drive. Double click on the file, load in defaul browser and copy the file address from the browser's address bar.
On the design page, double click on the main form and insert:
WebBrowser1.Navigate("")
- inside the quotation marks paste the file address. You can always use a website if you prefer it instead.
Double click on the "Change" button, add this inside:
WebBrowser1.Document.Body.Style = "background-color:green"
Double click on the "Active" button, add this to the sub:
TextBox1.Text = WebBrowser1.Document.ActiveElement.Style
- start program, click the "Change" button, the background color of the html's body should change.
Click on the page's background, then click the "Active" button. You should get "BACKGROUND-COLOR: green" into the textbox. If an element does have a specific style written in the html code, then the "style" property will retrieve it, otherwise you'll get nothing.
We can't use this line directly:
WebBrowser1.Document.GetElementsByTagName("div").Style - because GetElementsByTagName takes a group of elements, not a specific single one we would like to change.
Change the content of the button1 sub into this:
WebBrowser1.Document.GetElementById("885037_gm4").Style = "background-color:blue"
- the "GetElementById" method points to a single element determined by it's id, that's why the "style" property will work. If you want to know all the possible styles you can set for a web page, look for "CSS" in google. CSS stands for: "Cascading Style Sheet". CSS Resource Page. It's standardly used in the html code to change the display of html elements. It is also used to reduce the repetitive code of html elements.
(If you are navigating a website, you will have to find an id in the source code to test the above line)
This would also work:
WebBrowser1.Document.GetElementsByTagName("input").Item(1).Style = "background-color:blue"
- the second "input" element is going to be changed
Change the code of the button1 sub again:
For Each i In WebBrowser1.Document.GetElementsByTagName("input")
i.Style = "border: 2px solid rgb(255,0,0)"
If i.GetAttribute("id") = "885037_gm4" Then
i.Style = "background-color:yellow"
End If
Next
- start program, press "Change" button. All the "input" elements will get their background changed. Also, when the "id = "885037_gm4" is found, then the old styling of that element removed and the new will be inserted. This happens because we don't append to the new style, so we end up replacing it.
In order to add a new style to the old one, take this line from the "For Each" loop:
i.Style = "background-color:yellow"
and change it into this:
i.Style = i.Style & ";background-color:yellow"
- now the "input" element will get the new style while keeping the old one. Remember to write the semi-colon sign ";" when appending. After clicking the "Change" button, click into the input box and press the "Active" button.
Why it's better to append?
If the element doesn't have any CSS code, then giving it a complete new style rather than appending it will not make any difference: the html element will just receive the new style.
If we are only changing the background color and the only styling code that the element has is the background color, then everything is fine again: we will just set a new background color.
The problem starts when the element has more CSS style elements than the ones we are trying to change, or if it has different ones than the ones we are trying to change.
for example, a html element might have a style set for the border, margin, padding, font and display while we are just trying to change it's background with: i.Style = "background-color:yellow" -> this will erase all the previous style code and only insert the background-color: yellow inside. That's why it's better to use: i.Style = i.Style & ";background-color:yellow" in order to add the new style to the previous ones or to only change the background, if it's already present, without erasing everything else.
Add another button to the form on the right of the "Active" button, text: "Active Change", add this:
WebBrowser1.Document.ActiveElement.Style = "border: 2px dashed #31D4B8; background-color:MediumSeaGreen; font-family:Century Gothic"
- click on an element and then press the button. This is how we add more styles to the element with one single code line. You can use hexadecimal codes for colors as well, google: "hex color picker". The CSS language already has a number of color variants stored under very creative names: Check This Page.
Since not all elements in the source code have a defined style, it would be nice to find out the ones which do.
Add a button on the right of the "Active Change" button, text: Check For Styles, add this inside:
For Each i In WebBrowser1.Document.All
If Len(i.Style) > 0 Then
TextBox1.Text = TextBox1.Text & "Name: " & i.TagName & ", Style Length: " & Len(i.Style) & vbCrLf
End If
Next
- start the program, press the "Change" button, press the "Active Change" button and then press the "Check For Styles" button. Make the textbox larger if necessary.
This will give you the name and the style length of the elements that do have a style code. This loop might take it's time when used on websites with a high amount of data. The "Len" function returns the length of a string even if the value of the string is null (length will be zero).
You can't change the condition of the "if" statement to: i.Style.Length > 0 -> because when a null string is encountered, the "Length" property will not be able to process it and that will crash the program.
vbCrLf - is a visual basic constant for the new line, same as: "vbnewline"
Another variation of the above code would be:
For Each i In WebBrowser1.Document.All
If String.IsNullOrEmpty(i.Style) = False Then
TextBox1.Text = TextBox1.Text & "Name: " & i.TagName & ", Style Length: " & i.Style.Length & vbCrLf
End If
Next
- if the "Style" string is not null, then take the length of "Style" and insert it into the textbox.
We could have also used:
If i.Style IsNot Nothing Then ...
or
If i.Style <> Nothing Then ...
or:
If IsNothing(i.Style) = False Then ...
Erasing all the CSS style code from the html elements can be done this way:
If Len(i.Style) > 0 Then
i.Style = Nothing
End If
- using: i.Style = "" also works. Actually, inserting anything that is not a proper CSS style code into the ".Style" string will erase the whole styling code of the element. example: i.Style = "some random words"
We know now how to add a value to an element without any style code (adding with equality or appending), how to add a new value to an element that already has other style sets (append), how to change the value of an already present style set without erasing everything else (append), how to find which elements do have some styling code rather than none, how to erase the style code.
Once we have found the elements that do have the CSS code in them, we can search their strings for what we need. We might be looking for a certain style change in all of them like "background-color" (for any color) or a style change with a specified value like "background-color: red".
Add another button to the form, text: Change If Green, add this to the sub:
For Each i In WebBrowser1.Document.All
If IsNothing(i.Style) = False Then
If i.Style.Contains("BACKGROUND-COLOR: mediumseagreen") = True Then
i.style = i.style & "; background-color: red"
TextBox1.Text = i.style
End If
End If
Next
- press the "Active Change" button to change the background color then press this button.
- first "if" statement: we only check the elements that have the style code, second "if" statement: we use the "contains" function to find what we need within the string, if it's found, then the style is changed by appending the new one in.
It's very important to have the right character casing inserted into the "contains" function, otherwise we won't get what we want. The style property, on the left, has to have uppercase letters while the value of the property has to have lowercase letters. There is one colon and a space symbol between them.
Instead of using:
i.style = i.style & "; background-color: red"
we could have used the "Replace" function for changing strings:
i.Style = i.Style.Replace("BACKGROUND-COLOR: mediumseagreen", "BACKGROUND-COLOR: red")
Let's retrieve the value of a specified style element out of all the html elements.
Between the buttons on your from and the webbrowser, make some space for a textbox, no multilne is required, size around: 270, 20.
On the right of the textbox, add a button, text: Find, double click on it, add this:
Dim gg
Dim aa As String = ""
TextBox1.Clear()
If i.Style <> Nothing Then
gg = InStr(1, i.style, "BACKGROUND-COLOR")
If gg > 0 Then
gg = InStr(gg, i.style, " ") + 1
While Mid(i.style, gg, 1) <> ""
If Mid(i.style, gg, 1) = ";" Then
Exit While
End If
aa = aa & Mid(i.style, gg, 1)
gg = gg + 1
End While
TextBox1.Text = TextBox1.Text & "Element Name: " & i.tagname & ", Value found: " & aa & vbCrLf
aa = ""
gg = 0
End If
End If
Next
- start program, press the "Change" button, click on an "input" element without any background color, press the "Active Change" button, just make sure you have a few elements with background color changed, press the "Find" button. We used two functions for changing strings in this sub: InStr (Resource) and Mid (Resource).
First we declared the "gg" variable which contained the value 0, then we declared"aa" which had to have at least an empty value stored inside since we add characters to it later on. The "For Each" loop checks all elements, while the first "if" statement allows only the ones with the style code through.
gg = InStr(1, i.style, "BACKGROUND-COLOR") - InStr returns an integer value (a number). In our case, InStr starts at string index "1" (it must be at least 1, zero is not acceptable), it checks the "i.style" string and looks for the background term present as the third parameter. When that term is found, the index of the first character of the term ("B") inside the string will be returned. We store that number in "gg".
If the third parameter is not found, InStr will return zero.
If gg > 0 Then - the condition of this statement is only true if a background color has been previously found.
gg = InStr(gg, i.style, " ") + 1 - the new InStr function starts at the index position of the first character of "background-color" inside the string, then it looks for the next "space" symbol in the "i.style" string, once it's found, we get the index of that symbol and we raise the "gg" variable by 1. example: BACKGROUND-COLOR: red - the index will now be set to the "r" character, which is the beginning of the style value.
After that, we store the name of the element and the style value into the textbox. "aa" and "gg" are reset to their starting positions.
Instead of using:
gg = InStr(gg, i.style, " ") + 1
we could have used:
gg = gg + "BACKGROUND-COLOR: ".Length
"BACKGROUND-COLOR: ".Length - the "Length" property will calculate the number of characters present inside the quotation marks.
Inside the button6 sub, just below this declaration:
Dim aa As String = ""
add this:
Also, change this code line inside the "for each" loop:
gg = InStr(1, i.style, "BACKGROUND-COLOR")
into:
gg = InStr(1, i.style, bb)
- we store the content of the new textbox we added into "bb". If there was nothing written in the textbox - exit the sub. We change the casing of the text to uppercase ("Ucase(bb)") and also we remove all the potential "space" symbols at the beginning and at the end of the textbox text ("Trim(bb)").
Start the program. Change the style of a few html elements and then write into the new textbox something like this:
background-color
- lowercase, no colon sign, add spaces at the beginning and at the end. Press the "Find" button. Should work.
The problem is that we have to specify the exact name of the style, for example: border-bottom instead of just: border. Also, If we write, for example, "top" it will still give us the values of all the codes that contain the "top" term. This sub still needs some modifications to work properly.
Perhaps adding "-" at the end if there is no such symbol found in the textbox. Then we should retrieve all the instances of the "(one word)-" in the style code, determine the properties and also get their values.
Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WebBrowser1.Navigate("file:///D:/Elements.html")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each i In WebBrowser1.Document.GetElementsByTagName("input")
i.Style = "border: 2px solid rgb(255,0,0)"
If i.GetAttribute("id") = "885037_gm4" Then
i.Style = i.Style & ";background-color:yellow"
End If
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
TextBox1.Text = WebBrowser1.Document.ActiveElement.Style
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
WebBrowser1.Document.ActiveElement.Style = "border: 2px dashed #31D4B8; background-color:MediumSeaGreen; font-family:Century Gothic"
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
For Each i In WebBrowser1.Document.All
If String.IsNullOrEmpty(i.Style) = False Then
TextBox1.Text = TextBox1.Text & "Name: " & i.TagName & ", Style Length: " & i.Style.Length & vbCrLf
End If
Next
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
For Each i In WebBrowser1.Document.All
If IsNothing(i.Style) = False Then
If i.Style.Contains("BACKGROUND-COLOR: mediumseagreen") = True Then
i.style = i.style & "; background-color: red"
'i.Style = i.Style.Replace("BACKGROUND-COLOR: mediumseagreen", "BACKGROUND-COLOR: red")
TextBox1.Text = i.style
End If
End If
Next
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim gg
Dim aa As String = ""
Dim bb As String = TextBox2.Text
If bb = "" Then
Exit Sub
End If
bb = UCase(bb)
bb = Trim(bb)
TextBox1.Clear()
For Each i In WebBrowser1.Document.All
If i.Style <> Nothing Then
gg = InStr(1, i.style, bb)
If gg > 0 Then
gg = InStr(gg, i.style, " ") + 1
While Mid(i.style, gg, 1) <> ""
If Mid(i.style, gg, 1) = ";" Then
Exit While
End If
aa = aa & Mid(i.style, gg, 1)
gg = gg + 1
End While
TextBox1.Text = TextBox1.Text & "Element Name: " & i.tagname & ", Value found: " & aa & vbCrLf
aa = ""
gg = 0
End If
End If
Next
End Sub
End Class