In this article we will solve jQuery challenges and learn the jQuery syntax in this process.

1. Select all heading elements(h1-h6) and wrap it’s text in a span tag with a “text-xl text-green” classes, but wrap the text only till the “-” character

$(':header').html((index, txt) => {
  const text = txt.replace(/(.*)(-)/,'<span class="text-xl text-green">$1</span>$2');                            
  return text

I used the :header selector jQuery extension that selects all header elements(h1-h6). The html() method in jQuery can take besides an HTML string, also a function where we return an HTML, with index and html as arguments. I needed to use html() instead of the text() method because even if I get a string I will return eventually text and also a <span /> tag. I replaced with regular expression matching any text that comes before a dash with a span tag wrapper around that certain text.

2. Find all <li> tags with string values and insert them in a newly created <ul> after this list. Also add a hidden attribute to <li> tags that have number values lower then 0.

const list1 = $('#list1');
const list2 = $('<ul />').insertAfter(list1);
$('li', list1).each((i, item) => {
  const itemValue = $(item).text();
  if($.isNumeric(itemValue)) {
    if(itemValue < 0) {
      $(item).attr('hidden', true);
  else {

The $(‘<ul />’) method is like the createElement method in vanilla javascript. I created a <ul> tag and added after the first list. After that I iterate through all <li> tags in the #list1 list tag, get the text inside of them and check if the content is numeric and if it’s a negative value then we add a “hidden” attribute on it. If it’s not a numeric content then append the <li> item to the second list.

The original html is this:

And the result:

3. Swap “language from” and “language to” in a translation mechanism when you click on a button.

const swap = function(from, to) {
    return $(this).each(item => {
        const swapFrom = $(from).clone(true);
        const swapTo = $(to).clone(true);
let swappables = ['#lang1', '#lang2'];
$('#swapButton').click(() => {
  swappables = swappables.reverse();

I used the clone() method with the true argument, meaning that it will clone the element with all events and data on it. Then I used the replaceWith() method that takes the first element and replaces with the second element, the first element will seize to exist, but since we stored the clones for both of them in variables, nothing is actually lost when swapping. For toggle the order of what should be replaced with what, I added the reverse() javascript method, to swap also.

You can also remove the reverse() method and just use classes and the eq() order filter:

$('#swapButton').click(() => {
  swap('.lang:eq(0)', '.lang:eq(1)');

4. Load a json with fruit and vegetables and create a select box with options for these values. Wrap in the select box the fruit options in an optgroup with the label “fruits” and vegetables in an optgroup with the label “vegies”

$.getJSON('https://6367a46ef5f549f052d93df3.mockapi.io/api/getItems/shoppinglist', data => {
  const items = data[0].items;
  let selectItems = '';
  items.forEach(obj => {
    selectItems += `<option>${obj.item}</option>`
  const selectbox = $(`<select>${selectItems}</select>`)
  $('option:gt(1):lt(3)').wrapAll('<optgroup label="fruits"/>')
  $('select > option:gt(1)').wrapAll('<optgroup label="vegies"/>')

The $.getJSON method is actually an ajax call with json data type, then I constructed the string with the options with vanilla javascript. The selectbox constant holds a newly created select box tag that has the options string inside as html. Finally we append the select to the DOM and group from 3rd(JS is 0 based, so it starts from 0 instead of 1) to 5th element inside of an optgroup element. After these elements were moved starting from 3rd option till the end into another optgroup element.

Voila! Take a look at the result:

5. Scroll to element when clicked on anchor link

$('#anchors a').click(ev =>{
    const target = $(ev.target).attr('href');
    const targetPos = $(target).offset().top;
      { scrollTop: targetPos }, 'slow'

I used here the preventDefault() method from jQuery’s event object that prevents the click to follow the link/anchor. After that I took the href attribute, you can also use just vanilla JS (this.href). The offset() method can have top, left properties. The animate method simply animates the properties you provide in the brackets.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: