Selecting specific elements based on their position within a parent element using

I can't seem to figure out the strange behavior of the nth-child selector.

After calling the function BackColor1(), my visual appears different than expected:

Something seems off. However, when I call BackColor2(), everything looks normal again.

Could someone please help me understand what went wrong with the BackColor1() function?

Below is the HTML code sample I am working with:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        //BackColor1();
        //BackColor2();
    });
    function BackColor1() {
        $("li:nth-child(2n+1) > div").css({ "background": "#F2F2F2" });
    }

    function BackColor2() {
        $("li").each(function (key, val) {                
            if (key % 2 == 0) {
                $(this).children("div").css({ "background": "#F2F2F2" });
            }
        });
    }
</script>
</head>
<body>
<ul>            
    <li>
        <div>Video Streaming</div>
        <ul>                            
            <li><div>VOD</div></li>                            
            <li><div>Progressive Streaming</div></li>                                                                        
        </ul>                            
    </li>                    
    <li><div>Middle Lesson Without Chapter</div></li>                    
    <li>
        <div>File Download</div>                        
        <ul>                            
            <li><div>Direct Download</div></li>                            
        </ul>                            
    </li>                    
    <li><div>Pre Last Lesson Without Chapter</div></li>                    
    <li><div>Last Lesson Without Chapter</div></li>
</ul>
</body>
</html>

Answer №1

To optimize your code, consider utilizing the even selector

Here is an example:

function ChangeBackgroundColor() {
    $("li:even > div").css({
        "background": "#F2F2F2"
    });
}

Check out the demo

Answer №2

The reason for this behavior is that the nth-child selector counts from the beginning of each parent ul element.

<ul>            
    <li> <!-- first child of parent ul-->
        <div>Online Shopping</div>
        <ul>                            
            <li><div>Fashion</div></li> <!-- first child of nested ul-->
        </ul>                            
    </li>                    
    <li><div>Artisan Goods</div></li> <!-- second child of parent ul-->
    ...

Answer №3

The reason behind this phenomenon is that the VOD item being the initial offspring of its parent, naturally inherits the color scheme designated to it. This process fails to acknowledge the presence of neighboring elements.

On the other hand, your jQuery selector encompasses ALL list items across the entire webpage as a unified entity, resulting in the alternation of colors regardless of their location within the DOM hierarchy.

Answer №4

When utilizing the nth-child selector for BackColor one, keep in mind that each element's child number is determined by its parent. Therefore, when nesting lists, there is a possibility of encountering multiple LI elements being identified as nth-child = 1 and onwards.

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

blur event triggered on a cell within a table

Currently, I am using the code snippet below to populate data using a data table. My goal is to be able to edit the data in one of the columns and then validate the value after editing using the onblur event. I attempted to call the onblur event on the t ...

Tips for creating semi-circular shapes using CSS gradients

I am trying to design a div element with a background made up of two colors divided by a half circle: My preference is to use gradients for easier animation purposes. I am looking to avoid using pseudo-elements or border-radius, and my HTML structure limi ...

Make the text stand out by highlighting it within a div using a striking blue

Currently, I am working with Angular2 and have incorporated a div element to display multiple lines of text. Positioned below the text is a button that, when clicked, should select the entirety of the text within the div (similar to selecting text manually ...

The curious case of unusual behavior in jQuery's livequery() method

When attempting to use the jQuery plugin "livequery" to highlight certain words within dynamically generated search results, the highlighting does not appear to work! Strangely, adding an alert() function before executing the code causes the highlighting ...

Issue encountered with the ".replaceWith" method not functioning properly when incorporating the "nl2br()" function and inserting the "Enter" key within database text

I am facing an issue with editing text displayed from the database. When the text is in one line, the "Edit Text" button works perfectly. However, if I use an enter to create a new line in the text, the editing functionality does not work as expected. To ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

Enable AJAX to dynamically load pages without caching

I am currently using an ajax function to refresh a specific division on a webpage with HTML content. <script> $('#scene_container').load('scene.html', function () { cache: false }); </script> ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

What methods can I use to emphasize three distinct dates?

I'm facing difficulty highlighting three specific dates: "10-11-2020", "22-11-2020", and "07-11-2020" using React.js and Datepicker. Unfortunately, my attempts have not been successful so far. Here is the code snippet I am working with: import React, ...

Dealing with jQuery JSON AJAX Error Handling for Data Response

Looking to generate a dynamic select input (dropdown menu) from JSON data. I've experimented with two methods to obtain a JSON object for the dropdown menu Select input, labeled Attempt 1 and Attempt 2 in the commented out JS code. Although I am abl ...

Troubleshooting WooCommerce's AJAX Error Notification

In the online store I manage, there is a fixed header. If all required fields are not completed at the checkout page, Woocommerce displays an error message using Ajax. However, this message scrolls all the way to the top of the body, ignoring the custom CS ...

What is the best way to modify the glyphicon within the anchor tag of my AJAX render property?

Consider the use of Ajax: "target 0" with a render option for an anchor tag. Initially, I am utilizing the class "glyphicon glyphicon-chevron-right". Now, I wish to change it to "glyphicon glyphicon-chevron-down" when clicked. $(document).ready(funct ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

In NextJs SSR, external components from a different package do not inherit styles when applied

I have incorporated an external react component into my Next.js app code. Here is a snippet of how the component appears: <AppBar className={clsx(classes.header)}> </AppBar> export const header = makeStyles((theme) => ({ header: { ...

Retrieve the text label from the parent option group

Below is the HTML code snippet: <select id="categoryg"> <optgroup label="Main" value="binding"> <optgroup label="Sub" value="binding"> <option value="46&quo ...

Specify padding or margin for all sides in a single line of XML code

Is there a way to set the padding or margin for all four sides in xml with just one line, similar to how we can do it in css? For instance, in css: padding: 1px 2px 3px 4px; Is there an equivalent method in xml for accomplishing this? ...

Manipulating elements repeatedly using jQuery

One of the issues I encountered while working with jQuery was appending a YouTube video when a button is clicked. To do this, I used the following code: onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.yout ...

The rules for prioritizing CSS selectors

Struggling with CSS selector rules and specificity? I've already checked this for specifics. Even tried using firebug and inspecting elements in Chrome to copy the CSS path, but still can't get it to work. This is my first time creating a website ...

Checking for correct HTML tags using JavaScript

Looking to validate some input in javascript and confirm if it is a valid HTML tag. Any straightforward methods with JQuery for this task? If not, any suggestions on how to achieve this using Regex? Thank you! ...