Javascript code replacing page content when run from the address bar
For the hell of it, I decided to write
for(var i =0;i<document.getElementsByTagName("p").length;i++){
document.getElementsByTagName("p")[i].style.textTransform = "uppercase";
}
I was going to send this to someone as a joke. It's supposed to ma开发者_如何学Goke all the text on the page uppercase.
What I don't understand is: Why does the entire content of the page get replaced with the word "uppercase" when I run this from the address bar?
javascript:for(var i =0;i<document.getElementsByTagName("p").length;i++){ document.getElementsByTagName("p")[i].style.textTransform = "uppercase"; }
javascript:for(var i =0;i<document.getElementsByTagName("p").length;i++){ document.getElementsByTagName("p")[i].style.textTransform = "capitalize";void(0);}
Capitalize all words within paragraphs.
If you want to paste it in the address bar try:
javascript:(function(){
for(var p=document.getElementsByTagName("p"),n=p.length; n--;){
p[n].style.textTransform = "uppercase";
}
})()
Not exactly sure why it didn't work from address bar (at least in Chrome), but it will if you call it from a function. There could be a scoping issue, or it could have something to do with the for
construct. Regardless, if you wrap it in an anonymous function call, it'll work.
If your whole document is made of p
tags, then you are making everything in those tags uppercase
.
See this http://jsfiddle.net/jasongennaro/Y6nn2/
What did you want to happen?
精彩评论