During routine web programming or UI Automation scripting, it is often necessary to determine the display state of the page elements to perform the corresponding actions. This article mainly to JS to judge the existence of page elements as an example, a brief description of how JS is to determine the state of the display of elements, please refer to the small owners. If there are shortcomings, please the great God to correct it, greatly appreciated!
Many do not say, small two on the code slightly.
The following is a simple HTML source code, as follows:
1 <HTML>2 <Head>3 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">4 5 <title>JavaScript Operations Common web elements three-judging element display status</title>6 </Head>7 8 <Body>9 <Div>Ten <h4ID= "P1">Show/Hide:</h4> One <ul> A <Li>Hidden text: document.getElementById (' P1 '). style.visibility= ' Hidden '</Li> - <Li>Display text: document.getElementById (' P1 '). style.visibility= ' Visible '</Li> - </ul> the <inputtype= "button"value= "Hidden text"onclick= "document.getElementById (' P1 '). style.visibility= ' Hidden '" /> - <inputtype= "button"value= "Show text"onclick= "document.getElementById (' P1 '). style.visibility= ' Visible '" /> - </Div> - + <Div> - <BR><BR><BR><BR> + <ahref= "Http://www.w3school.com.cn/jsref/dom_obj_style.asp"Target= "_blank">HTML DOM Style Object</a> A </Div> at </Body> - </HTML>
The page shows the effect as follows:
When a page element is displayed, its corresponding CSS style is as follows:
Display:
Hidden:
Through observation, it is found that the corresponding values of the Sytle.visibility attribute can be judged by the element, and the corresponding value of the above three cases is obtained by JS as follows:
Comparing the above three results, the substr (start, length) or substring (start, end) can be obtained by JS to intercept the value of visibility, but this method is not advisable for the first case. Therefore, it is more concise and convenient to use the method of String.IndexOf (' string ') to get the position of the string, if the query string exists, the corresponding index is returned; otherwise, 1 is returned. The actual validation results are as follows:
Pro, this method can be further encapsulated to facilitate subsequent operation, improve coding efficiency.
At this point, the js-004-javascript operation of the common web elements of the four-judging element display status is successfully completed, I hope this article can give beginners JavaScript you a reference.
Finally, very grateful to the pro-stop, I hope this article can be pro helpful. Warmly welcome the kiss to discuss together and progress together. Thank you so much! ^_^
Js-004-javascript operation Common Web element four-judging element display state