I am trying to call a google ad sense code inside an article, But i don't want to past ad sense code in middle of an article. For that i am trying some thing like bellow, but it is not working as i expected because of java script issues.
<script> var x = document.getElementById("myArticle").querySelectorAll("p"); x[1].insertAdjacentHTML('beforeBegin', '<script>document.write(2+1)</script>' ); </script>
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
The problem is that the </script>
inside your string terminates the script.
You can use something like "</sc" + "ript>"
or "<\\/script>"
to prevent this.
var x = document.getElementById("myArticle").querySelectorAll("p"); x[1].insertAdjacentHTML('beforeBegin', '<script>document.write(2+1)<\\/script>' );
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
Note that the script in script
elements inserted like this won't run automatically. If you want to run some string, you can use eval
. Use it carefully.
eval('document.write(2+1)');
<div id="myArticle"> <p>A heading with class="example" in div</p> <p>A paragraph with class="example" in div.</p> <p>A paragraph with class="example" in div.</p> </div>
You shouldn't use document.write
, though. See the warning in the spec .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.