Reputation: 1007
i have 4 divs , i want to get the clicked div and change it's style , my divs are dynamically created that is why I don't want to use the id
<div class="item">Lorem ipsum 1</div>
<div class="item">Lorem ipsum 2</div>
<div class="item">Lorem ipsum 3</div>
<div class="item">Lorem ipsum 4</div>
jquery code :
<script type="text/javascript">
$('.item').on("click", function() {
// change style
});
</script>
Upvotes: 1
Views: 78
Reputation: 82251
You need to use event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$('body').on("click",'.item', function() {
// change style
});
Upvotes: 5
Reputation: 399
We first include jquery library.Then we style using css on jquery click event.
<script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$(".item").click(function(){
$(".item").css("color", "red");
//we can style anything .css('property','value');
});
});
</script>
</head>
<body>
Upvotes: 0
Reputation: 2867
$(document).on("click", ".item", function() {
var elt = $(this);
// do whatever you want with elt.css()
});
This way, you will catch every click event on any .item
element, whenever the element is created (added to the page via ajax for instance)
More info about it on jQuery Event Deleguation doc
Upvotes: 1