Choose the initial element that has a unique label

Looking to create a custom CSS class that will apply a background color only to the first element with a specific tag...

This is what I have so far:

.blue p:first-of-type {
    background-color:#2E9AFE;
}

It works in this scenario:

<div class="blue">
    <p>element 1</p>
    <p>element 2</p>
    <p>element 3</p>
</div>

But doesn't work with this example:

<div class="blue">
    <ul>
        <li><p>Parent 1</p>
            <ul>
                 <li><p>Element 1.1</p></li>
                <li><p>Element 1.2</p></li>
            </ul>
        </li>
    </ul>
</ul>

In the second example, the first p tag is "Parent 1", yet my code applies the color to all elements. Why is this happening?

Fiddle: http://jsfiddle.net/alexix/CYX32/1/

Answer №1

When you use the :first-of-type selector, it targets the first element of that type within its parent element. For example, in this case, the p is the first of its type within each li element.

If you want to specifically target the first p within the first li within the first ul, you will need to utilize the following CSS selector:

.blue > ul:first-of-type > li:first-of-type > p:first-of-type {
    background-color: #2E9AFE;
}

Check out the JSFiddle demo here.

Answer №2

To highlight the first occurrence of a p tag without knowing its exact location, using JavaScript may be the only solution.

JavaScript:

var blue = document.getElementsByClassName('blue')[0];
var p = blue.getElementsByTagName('p')[0];
p.className = 'blueContent';

CSS

.blueContent {
    background-color:#2E9AFE;
}

View the Working Example

Answer №3

We suggest giving it a shot:

.blue > ul > li > p {
    background-color:#2E9AFE;
}

Answer №4

Need a solution using jQuery? Check out this approach:

$(document).ready(function(){
    $('.blue').each(function(index, obj){
        var $p = $(this).find('p').eq(0);
        $p.css('background-color', '#2e9afe');
    })
});

Check out the demonstration here!

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

Maintain the aspect ratio of an image within a flex container when the height is adjusted

I'm currently facing an issue with an image in a flex container. My goal is to maintain the image's ratio when the height of the container or window is decreased or resized. Check out this sample fiddle html, body { height: 100%; } .wrappe ...

The value of the ng-model checkbox does not update or change when the checkbox is clicked

There is a checkbox being used in the code snippet below: <input type="checkbox" ng-click="toggleShowOtherUserConfiguration()" ng-model="showOtherUserConfiguration" name="ShowOtherUserConfiguration" value="showOtherUserConfigurati ...

Resizing background images to their original size using jQuery

Can anyone help me figure out the actual size in pixels of a background image that is being displayed? <style> body { background-image: url(background.jpg); background-size: contain; } </style> I tried using jQuery to get the size of ...

Looking to create a toggle button to show more or show less dynamic API data in a React component?

I have a specific requirement for my web page where I have multiple tabs, each of which displays dynamic data obtained from an API. The data is constantly changing on a daily basis. Within each tab, there is a rectangular box with a fixed height, and below ...

Serious issue: a dependency request is an expression (Warning from Angular CLI)

I am currently exploring the dynamic loading of lazy child routes within a lazy routing module. For example: const serverResponse = [ { path: "transaction", children: [ { path: "finance", modulePath: &qu ...

Pass on the touchmove event from the panel to the content using jQueryMobile

Within my interface, I have a link labeled myLink located in a side panel labeled myPanel, along with some content labeled myContent. My goal is to: Tap and hold on the link myLink within the panel myPanel Have the panel myPanel close immediately Add an ...

Tips for aligning a div in the center while adjusting screen size

My goal is to showcase a dashboard with a card layout. The desired layout can be seen https://i.sstatic.net/OWgpE.png: Here is a snippet from the HTML File: <div id="overallCanvasWrapper" class="statistic-container"> <p ng-show=" ...

Is Jquery "resistant" to updating CSS properties?

Within my HTML document, there exists a div with the class fd-video-upload-box, which has the following style properties applied: background-color: rgb(236, 238, 239); outline: 1px dashed gray !important; Upon rendering, it displays correctly as intended ...

Error in Function Due to Undefined jQuery DataTable Parameters

In the jQuery datatable column, the below JavaScript code will display either a green checkmark button or a red X button: { data: "HasPayment", render: function (data, type, row, meta) { if (data) { return '<bu ...

Guide to redirecting traffic from one domain to another while preserving the path component

I am looking to create a redirection from one subdomain to another while keeping the same path intact. I am using a blogging platform and do not have access to a server, but I can modify the global head section of my blog. Currently, I am able to redirec ...

Placing HTML text on top of a three.js renderer

I have been attempting to overlay HTML text onto my three.js sketch, but adjusting the z-index does not seem to be working. While I know that I could utilize innerHTML, the issue arises when I need to also use the onclick attribute, which is not the main f ...

The pdfkit library seems to have an issue where it is failing to properly embed images within the

Currently, I am working on using PDFkit along with node.js for converting an HTML webpage into a PDF format. The HTML page contains multiple image tags within the body tag. Unfortunately, when I convert the HTML to PDF, the resulting page appears complete ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Choosing a sequence of text snippets divided by the <br> tag found inside a specific class

Is there a way for me to extract each of those strings using jQuery or JavaScript? For example, 'fight club', 33 Main Street, Houston, etc. <span class="cart_text2"> Fight Club <br> 33 Main Street, <br> Hou ...

Stop options from being hidden in a select dropdown using HTML

Can I keep the options visible when a user selects an item in the 'select' dropdown? I want to add more options to the 'select' when the user clicks on the 'op2' item, without closing the list of options. <select> <o ...

Is it possible to merge node modules that have similar functionalities?

When utilizing node.js, you may encounter module dependencies containing functions with similar functionalities, such as underscore, lodash, and lazy (potentially in different versions). Is there a way to specify which module from a group of similar metho ...

Eclipse Content Assist feature appears to be malfunctioning as it fails to display

Having an issue with Eclipse on Win 10 (64bit) when working with JavaScript projects. I've tested this problem on both Eclipse Photon and version 2018-09 (64 bit versions) and encountered the same problem on both instances: After creating a new JavaS ...

Guide on crafting a scrollable and touch-responsive grid using CSS and JavaScript

I am seeking guidance on creating a grid with a variable number of columns and rows. It should be contained within a separate div and should not interfere with other objects or alter the parent's size. The grid needs to be square and I am currently u ...

Tips for showcasing a search bar on Google search results

While browsing in Google, I came across websites that have a search bar displayed after their initial search result. This functionality allows users to easily search within the website as shown in the image below. I am intrigued and wondering how this can ...

Creating Tabbed Navigation with CSS - A Step-by-Step Guide

I am looking to create tab contents using CSS. I have managed to create a custom tab style, but I am struggling to style its content with CSS. Can anyone provide guidance on how I can achieve this? CSS: .tabs { list-style: none; margin: 0; pa ...