Hello guys I have stuck with this example I dont understand what happens after assigning the var classNames. What role plays the attr("class") and split?
$(document).ready(function() {
$(".box").on("click", function() {
var classNames = $(this).attr("class").split(" ");
$("." classNames[1]).css("background-color", "red");
});
});
CodePudding user response:
If I understand your question correctly, both methods have different "roles".
The attr() method is used to get attribute values-in particular, the value associated with "class". The attr() method is typically used in DOM manipulation.
The split() method is used to split text or put another way to split a string into an array of substrings. The split() method does not modify the original string but returns a new array
CodePudding user response:
Consider this example. attr("class") gets all the classes the tag has and split makes an array of them so you can reference them by index: classNames[1]
In this example, classNames[1] is the class center and adding .css("background-color", "red"); to it is equivalent to .center{ background-color:red; }
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
.box {
color: green;
font-size: 32px;
}
</style>
</head>
<body>
<button value="click">Click</button>
<script>
$(".box").on("click", function() {
console.log($(this).attr("class")); //returns 'box center'
var classNames = $(this).attr("class").split(" ");
console.log(classNames); //returns ['box', 'center']
$("." classNames[1]).css("background-color", "red");
});
</script>
</body>
</html>
