I have a long list elements <li> in my html code:
<li class="pl1"><a href="#">some</a></li>
<li class="pl2"><a href="#">something</a></li>
<li class="pl3"><a href="#">something1</a></li>
And somewhere else in html code objects:
<span id="pl1">.</span>
<span id="pl2">.</span>
<span id="pl3">.</span>
And I wrote a script that adds class named focus in according pattern:
$("li.pl1").mouseenter(function() {
$("#pl1").addClass("focus");
});
$("li.pl2").mouseenter(function() {
$("#pl2").addClass("focus");
});
$("li.pl3").mouseenter(function() {
$("#pl3").addClass("focus");
});
The only problem is that the code would have to be long. How to write a short jQuery code according to this pattern?
I agree with BNL’s approach…if at all possible modify your html so that you use the same class. However if that isn’t possible you could try using the starts with selector:
This will give you what you want (I think) but there are better ways to do this. For instance I’m not sure what will happen if you start adding classes to your LI’s.
Using an attribute that starts with “data-” is a generally accepted way of passing information into your function. If you have the ability to change your html you may want to consider:
Then the jquery changes to: