Article

Acting on Each Element in a Selection

https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
Copy to clipboard

When you want to select an element using jquery you may use class name.

This presents some challenges because when we have multiple items with the same class name but we only want to apply a jquery function to some specific elements with that class.

Suppose our Webflow list needs to be modified so that all items that start with the letter "L" are highlighted with a red color. To do this we use the each() function like so: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/jquery%20functions/ex16.js?actionable=true

In the above code the each() takes has a function inside it. Inside this function we define an if condition to check whether an element has L as part of its text. The special keyword this is used to denote the current li element that we are checking.

If the current element has L in its text then, the code would change the color of the text in the li element to red using the command $(this).css('color', 'red').

Sometimes Jquery's when described well, is powerful enough to implement complex code without the use of each() function or even if statements.

The code above can be rewritten simply written as: https://raw.githubusercontent.com/finsweet/jqueryCourse/main/jquery%20functions/ex17.js?actionable=true A slight difference is the code above checks for uppercase L anywhere in the text and not whether the list item starts with uppercase L.

<script>
$(document).ready(function(){
  XT1
});
</script>
Copy to clipboard
Send to Live Demo

Live demo

<style>#buy{color:#baff00;} #buy:hover{text-decoration:underline;} .highlighter{background-color: rgb(186 255 0 / 17%);}</style><div id="minidivpage" class="example-live"><h1 class="heading">This is a heading</h1><div id="popUp" class="pop-up">POP UP DIV</div><h4 class="heading-4">Categories in a webflow list:</h4><ul role="list" class="list"><li>Location</li><li>Position</li><li>Level</li></ul><h3 id="title" class="heading-3">This is a title</h3><div class="highlighter"></div><a id="buy" target="_blank" href="#">Link</a></div>

<script>    
$(document).ready(function() {
  XT1
});
</script>
<script>
  
</script>
Copy to clipboard
Press the Run Demo button to execute the scripts above.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Your browser is too small

Resize your browser to be at least 769px wide.