What is the best way to select a clicked span element within a div using JQuery and then adjust the spans before and after it

<div>
<span>A</span>
<span>B</span>
<span>C</span>
<span>D</span>
</div>

If a user clicks on one of the spans within the div, I want to apply styles (such as text color) to that span and all preceding spans inside that same div. Additionally, I want to remove any previous styling applied to other clicked spans. The spans do not have any classes or IDs.

How can I achieve this functionality using jQuery?

Answer №1

If you want to select all previous sibling elements of the clicked element, you can utilize the prevAll() method. However, if you also wish to include the clicked element itself, you will need to add andSelf(). Additionally, it is important to remove the background from all span elements each time a span is clicked.

$('div span').click(function() {
  $('div span').css('background', 'none');
  $(this).prevAll().andSelf().css('background', 'red')
})
body {
  padding-top: 10px;
}
span {
  cursor: pointer;
  padding: 10px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>A</span>
  <span>B</span>
  <span>C</span>
  <span>D</span>
</div>

Answer №2

Take a look at this JSFiddle code snippet to see if it can assist you.

JavaScript:

$('span').click(function(){
    $(this).siblings().css('color','')
    $(this).css('color','red');
  $(this).prevAll().css( "color", "red" );
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display <iframe> containing a YouTube video on Mozilla Firefox page

I have included an <iframe> in my webpage to display videos from YouTube, but I am facing an issue with Mozilla Firefox. In Chrome, IE, and Edge, the videos display correctly using the following code: <iframe src="http://www.youtube.com/v/DNLh8p ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...

Can we keep a portion of the input placeholder content?

The input box below accepts values in percentage form. To indicate this, I have set a placeholder that says Percentage (%). https://i.sstatic.net/LJ1ee.png My goal is to automatically add a % symbol to the value as soon as it is entered into the input fi ...

The <p> element nested inside a <div> element with font-weight styling

I'm struggling to make a large font size and weight fit into a div tag while aligning it vertically at the bottom. Can anyone help me with this issue? div { border:1px solid black; height:100px; } table { border:1px sol ...

What are the steps to interact with a marquee using Selenium?

Currently, I am faced with an application that displays a list of upcoming vessels in a marquee format. I am looking for a way to click on the specific data using Selenium with Java. Any advice or alternative solutions would be greatly appreciated. ...

Tips for retrieving the text value on keyboard enter press without triggering form submission

I am currently working on a feature where hitting the Enter key in a textbox should not automatically submit the form. The textbox is located within a form: @Html.TextBoxFor(model => model.ID, new { @class = "form-control input-sm", placehold ...

What is the best way to ensure that text stays aligned perfectly next to an

There seems to be a problem with my CSS. The text in the <li> tag is appearing below the line of the icon. How can I resolve this issue? I want the text to be vertically centered on the line. This seems to happen when I use the ::before selector with ...

IE9 encounters a setback with AJAX Jsonp request

Below is the code snippet I am working with: $.ajax({ type: 'POST', url: 'index.jsp', data: 'id=111', dataType: 'jsonp', success: function(data) { alert(data.result); }, error: f ...

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

Guide on implementing mouse Click event for 3-dimensional model

I recently added a 3D collada (.dae) file to my scene. This 'DAE' file includes geometry named "monster" with the id "monster-mesh-skin". I attempted to apply a mouse click event to the "monster" geometry using the following code: var monster = ...

HTML: Learn how to concatenate the href attribute of an anchor tag instead of replacing it

I am currently on the page www.myUniqueWebsite.com/sign-up?type=explore In the navigation menu, there is a link to switch languages. <a href="?lang=es">Spanish</a> When I click on this link, it redirects me to www.myUniqueWebsite.com/ ...

How can I eliminate excess cell spacing from a div that has a display of inline table?

This situation is really frustrating. While using Firefox and Opera, I am encountering unnecessary padding between my nested divs, which is not the case with Chrome and Safari. I attempted to use border-collapse:collapse However, it did not work. Do you ...

Controller for Ionic 3 styles and loading animations

What is the best way to eliminate these white spaces in our fullscreen mode? View the image here removeWhiteSpace() { let space = document.getElementById('white-space'); if (space) { space.style.display = 'none'; ...

Using a variable with the :contains selector

function checkAndUpdateStatus(newName) { $('#myTable').children('tr').remove(":contains('" + newName + "')"); }; The function above is attempting to remove table rows in 'myTable' containing a string matching the ...

Angular2 poses a strange problem with ngClass

It seems like Angular is expecting me to use single quotes for the class names even if there are no hyphens in my CSS class name. I've tried everything but Angular keeps insisting on using hyphens for this specific CSS class... it's strange, or m ...

Specify the input type to occupy the full width and be contained within its parent div

I'm currently dealing with a form that includes input fields for email and password, along with some additional buttons. Here is the HTML code: <div id="login-form"> <form> <input type="email" placeholder="Email" id="email" name= ...

Troubleshooting: Jquery UI Draggable - Cursor losing track of draggable element

I want to create a draggable popup with Jquery UI functionality, but I'm facing an issue where the cursor does not stay aligned with the popup element when dragged. When dragging the popup element to the left, the mouse cursor goes beyond the div elem ...

Is there a problem with the timing of jQuery rollover/out button functionality?

I have a setup in progress where a series of buttons with titles reveal more information on rollover. The layout features an intro section in the center, surrounded by the buttons. When hovering over any button, it triggers a function to hide the intro and ...

The Elusive Key to Perfect Layouts and its Transformation

Today I discovered the Holy Grail of Layouts while coding, but when I implemented it, the output in browsers was not as expected. The borders were incomplete and strange: Here is the code snippet that caused the issue: #container { border: 10px soli ...

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...