To add css style with an element
To add the css stylesheet, we can use css method and pass the name and value as the parameter. In the below code,
you can see that I have used css method and passed the attribute name and its value as parameter to the element I want to change.
<script>
$(document).ready(function() {
$("#jbtnChangeStyle").click(function() {
$("#jdivAddStyle").css("border", "2px solid #CC3300")
$("#jdivAddStyle").css("font-weight", "bold");
})
})
</script>
<div id="jdivAddStyle" class="demoBlock">This is the sample class</div>
<input type="button" value="Change CSS Style" id="jbtnChangeStyle" />
This is the sample class
Loop through each element
To loop through each elements, we can use each method. Here, you can see that onclick event of the button, I have got the parent element of the li element (ie ul id="jUlCount") and instructing to loop through each li element.
<script>
$(document).ready(function() {
$("#jbtnLoopLI").click(function() {
$("li").each(function() {
$(this).css("border", "1px dotted #FF0066");
});
})
})
</script>
<ul id="jUlCount">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Size</li>
</ul>
<input type="button" id="jbtnLoopLI" value="Loop through each number list" />
One
Two
Three
Four
Five
Size
Loop through all elements of a particular type
To loop through all element of a particular type, you can use get() method that returns the array of the elements. After getting the elements, you can loop through the array and get the desired text or inner html contents using innerText or innerHTML.
<script>
$(document).ready(function() {
$("#jbtnLoopAll").click(function() {
var lis = $("#ulLoop li").get();
var allLIs = [];
for (var i = 0; i < lis.length; i++) {
allLIs.push(lis[i].innerText);
}
$("#jspanAdd").text(allLIs.join(" "));
});
});
</script>
<ul id="ulLoop">
<li>Ram</li>
<li>Mohan</li>
<li>Gita</li>
<li>Ramanuj</li>
</ul>
<span id="jspanAdd" class="demoBlock"></span><br />
<input type="button" id="jbtnLoopAll" value="Loop through all elements of a particular type" />
In the above code snippet, you can see that I have get all the li element using "#ulLoop li", where #ulLoop" is the id of the parent element and "li" is the element I want to get. Here, if I want to loop through all "li" element of the page, I can use $("li").get() instead of $("#ulLoop li").get().
In this code snippet, you can see that I have used "push" method to add values into the array and "join" method to join all the values of the array.