开发者

AddClass to <a> using jquery

I am trying to add a Class to the first link.

The code looks like this:

<p class="breadcrumb"> <a href="index.php"> Home </a> <a href="contact.php">Contact</a>

开发者_如何学PythonI don't know how to add a class to the first link "Home" (index.php) so i could style it with css.

<script type="text/javascript" charset="utf-8">
$(".breadcrumb a:first").addClass("itemhover");
</script>

This did not work.


The element probably hasn't loaded. Delay your Javascript until all elements have been loaded with $(document).ready():

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
    $(".breadcrumb a:first").addClass("itemhover");
});
</script>


Wrap the code in document ready.

<script type="text/javascript" charset="utf-8">
$(function(){
    $(".breadcrumb a:first").addClass("itemhover");
});
</script>


<script type="text/javascript" >
$(document).ready(function() {
$(".breadcrumb a:first").addClass("itemhover");
});
</script>


try adding an id to the link

<p class="breadcrumb"> <a id="home" href="index.php"> Home </a> <a href="contact.php">Contact</a>

and then try this:

$(document).ready(function() {
    $("#home").addClass("itemhover");
});


Your syntax are correct but there is some problem with CSS overriding you can use !important to you class attribute

example :

<script>
    $(function(){

        $(".breadcrumb a:first").addClass("itemhover");

    });
</script>



.itemhover{
        color : red !important;
}


Sample page :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" --"http://www.w3.org/TR/REC-html40/strict.dtd"-->
<html>
<head>
  <link type="text/css" rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css" />
  <script type="text/javascript" src="http://jqueryui.com/js/jquery.js"></script> 
  <script type="text/javascript" src="js/jquery-ui-1.8.6.custom.min.js"></script>

  <script>

    $(function(){
        $(".breadcrumb a:first").addClass("itemhover");
    });
  </script>

<style type="text/css">
.itemhover{
    color : red !important;
}
</style>
</head>
<body>

<p class="breadcrumb"> <a href="index.php"> Home </a> 
<br />
<a href="contact.php">Contact</a>
</P>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜