Reputation:
I have this jQuery code that works fine when placed between the <body>
and </body>
tags of the .HTML file.
</body>
tag.<head></head>
it is not working also.So I need help getting this JavaScript code to run externally.
<html>
<head>
<style>
.blue1 {background: green;}
.red {background: red;}
.orange {background: orange;}
.yellow {background: yellow;}
</style>
</head>
<body>
<table border="2px solid black">/*border*/
<tr>
<td colspan="1">
<p class="Hello_blue1">Hello Stack Overflow1</p>
</td>
<td rowspan="1" colspan="2">
<p class="Tab-Text-7-aufz_red">Hello Stack Overflow2</p>
<p class="Tab-Text-7_red">defines red color,that class want to apply
to</p>
</td>
<td rowspan="1" colspan="1">
<p class="Hello_orange">Hello Stack Overflow3</p>
</td>
<td rowspan="1" colspan="1">
<p class="Tab-Text-7_yellow">Hello Stack Overflow3</p>
</td>
</tr>
</table>
JavaScript which I want to use as External.js
<script>
// convert "Hello_blue" to "blue"
function convertClassName(src)
{
return src.replace(/^.*?_/, "");
}
var pTags = document.querySelectorAll("table p");
for (var i = 0; i < pTags.length; i++)
{
pTags[i].parentNode.className += " "
+ convertClassName(pTags[i].className);
}
</script>
</body>
</html>
Upvotes: 1
Views: 1451
Reputation: 177
Used the "onload" feature and link it to the "body" element.
<body onload="myFunction()">
myFunction() will start once the page loads
Or you can use this
$( document ).ready(function() {
$( "a" ).click(function( event ) {
alert( "You clicked !!!" );
});
});
Upvotes: 0
Reputation: 33
Yeah you can create a new file with .js extension and paste your code in that file. Then just write a code like, <script type="text/javascript" src="your path"> </script>
in head.
Upvotes: 0
Reputation: 3886
Create a new file (in the same folder as your HTML) called for example script.js
, which contains this:
function convertClassName(src) {
return src.replace(/^.*?_/, "");
}
var pTags = document.querySelectorAll("table p");
for (var i = 0; i < pTags.length; i++) {
pTags[i].parentNode.className += " " + convertClassName(pTags[i].className);
}
And leave this in your HTML:
<html>
<head>
<style>
.blue1 {background: green;}
.red {background: red;}
.orange {background: orange;}
.yellow {background: yellow;}
</style>
</head>
<body>
<table border="2px solid black">/*border*/
<tr>
<td colspan="1">
<p class="Hello_blue1">Hello Stack Overflow1</p>
</td>
<td rowspan="1" colspan="2">
<p class="Tab-Text-7-aufz_red">Hello Stack Overflow2</p>
<p class="Tab-Text-7_red">defines red color,that class want to apply
to</p>
</td>
<td rowspan="1" colspan="1">
<p class="Hello_orange">Hello Stack Overflow3</p>
</td>
<td rowspan="1" colspan="1">
<p class="Tab-Text-7_yellow">Hello Stack Overflow3</p>
</td>
</tr>
</table>
<script src="./script.js"></script>
</body>
</html>
Upvotes: 1