1

I have following code to change the style of an element, once I enter the page the alert window will be shown with "myP" message; whoever, the style wont get added to the element. Also, let me know if you have jQuery based solution for it.

<!DOCTYPE html>
<html>
 <body>
    <script type="text/javascript">
         alert("myP");
         document.getElementById("myP").style.fontWeight = "bold";
    </script>

    ...
    <a id="myP" href="www.example.com">Example</a>
    ...

    </body>

</html>
0

4 Answers 4

2

As requested by OP jQuery-based solution for waiting for the DOM to load would be

$(document).ready(function(){
    alert("myP");
    $("#myP").css("font-weight", "bold")
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer but Mritunjay posted his answer before you so I need to accept his answer.
1

That is because the document is not loaded at the time your JS code is being executed.

Wrap the javascript code to window.onload function like bellow

 window.onload = function(){
     alert("myP");
     document.getElementById("myP").style.fontWeight = "bold";
 }

Note:- Make a habit of looking at console.

Comments

1

Your script will run before the element is loaded. You need to wrap it in a function and call it when the document loads.

Comments

1

your element would not be found by the script as it would not have been loaded when you call getElementById on it, so move your script code before closing body tag, as:

<!DOCTYPE html>
<html>
 <body>      

    ...
    <a id="myP" href="www.example.com">Example</a>
    ...
    <script type="text/javascript">
         alert("myP");
         document.getElementById("myP").style.fontWeight = "bold";
    </script>
    </body>

</html>

Demo :: jsFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.