Unexpected behavior with first-child selector in a simple CSS code

It seemed so clear to me, but it turns out I was mistaken.

Check out this link

$('p:first-child').css({color:'red'});

The color of all text is not being altered.

<div class="post text"> <a href="#">this is a url</a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
</div>
<div class="post text"> <a href="#">this is a url</a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex optio velit culpa nisi nemo ab voluptatem vitae voluptate molestiae recusandae? Ipsa dolorum ut dignissimos ipsam doloribus itaque reprehenderit nostrum a.</p>
</div>

Answer №1

It needs to be

$('p:first').css({color:'red'});

Replace

p:first-child {
    background-color: orange;
}

with

p:first-of-type {
    background-color: orange;
}

Access the updated fiddle here.

Answer №2

It seems like you're searching for this:

$('p:first').css({color:'red'});

UPDATE:

Choosing the first <p> within any <div>

$('div p:first-of-type').css({color:'red'});

See Live Demo

Answer №3

Consider using the jQuery :first or :eq(0) selectors, for example:

$('p:first').css({color:'red'});

For a visual demonstration, check out this Demo and this Eq demo

Answer №4

Check out this code snippet:

$(document).ready(function() {
  $("p:first").addClass("first");
});

CSS : p.first { color: red; }

Answer №5

My approach to this issue involves targeting the initial p tag offspring of each main post. Here is the code snippet I recommend:

$('div.post p:first-child').css({color:'red'})

Answer №6

The css :first-child selector is utilized to target a specific selector only if it appears as the first child of its parent element.

Check out this fiddle for an example:

Here's the CSS code:

p:first-child {
    background-color: orange;
}

Answer №7

If you're looking for a clever solution, you can try adding this snippet of code to your jQuery script:

$('p:nth-child(2)').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

Arrange divs in vertical columns

My markup is fixed and I am only allowed to add <div> elements to the container. Here is the current structure: <div class="container"> <div class="box" id="box1">1</div> <div class="box" id="box2">2</div> < ...

Can you provide guidance on how to zoom in on the Jquery Portlet when clicking the "zoom-in" icon?

After thorough research in various forums, I have not come across any relevant post addressing my specific issue. Therefore, I am reaching out for assistance. I currently have four Jquery Portlets on my page. My goal is to enable a zoom-in feature on o ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Using JavaScript to modify a section of an anchor link attribute

I am looking to dynamically update part of the URL when a specific radio button is selected. There are three purchase links, each representing a different amount. After choosing an animal, I need to select one of the three amounts to spend. How can I modi ...

Locate all elements containing a specific text string

In an attempt to clean up html-elements, I am searching for specific text strings within 2376 html-documents. The documents have varying doctype standards, with some lacking a doctype altogether (which may not be relevant). I am specifically looking for t ...

When the flex-grow property is set to 1, the height of the div extends beyond the space that

Here is an example of some HTML code: .container { height: 100%; width: 100%; display: flex; flex-direction: column; padding: 10px; background-color: aqua; } .box { width: 100%; height: 100%; flex-grow: 1; background-color: cadetb ...

When a table row is selected, set the OnClick attribute of an input to the value of the TD cell in that row based on

I'm really struggling with this. So, here's the issue - I have a table where rows get assigned a class (selected) when clicked on. Now, there's an input inside a form that needs to redirect to another page when clicked, and it also needs t ...

Ways to select the initial 10 rows, final 3 rows, and middle 2 rows using Javascript

As a newcomer to Javascript, I have a couple of questions: 1) How can I retrieve the first 10 rows, the last 3 rows, and the 2 rows in the center using the code var firstTable = $('#aaa table').eq(0); 2) Is there a way to create and assign new ...

Utilizing Object Arrays in Chart.js for Optimal Performance

I'm struggling with using chart.js to create charts for my admin panel. I'm having trouble figuring out how to properly utilize my JSON array of objects in order to generate the correct dataset. What exactly should I be putting in the data field ...

Adjust the error message shown for a specific field in a jQuery form validator

I need to customize the error message for validating date of birth based on age. Specifically, I want a separate error message to show when the age is below 13. Currently, I have a jQuery validate addMethod function that calculates the age. Can you review ...

Refreshing CKFinder Form Field with jQuery

Looking to update the value of an input field .ckfinder-input using CKFinder's pop-up image selector. Everything runs smoothly until attempting to assign the selected image URL to the input field with input.val() = fileUrl, resulting in the error mess ...

position text to the right side of a slider gallery created with JavaScript

I'm currently utilizing a WordPress plugin known as Slideshow Gallery and I want to position the text below it to float next to the gallery on the right side. I've attempted the following: .bioText{ font-size: 14px; font-size: 1.428571429rem; ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Ways to display a div when a drop-down box is clicked

How can I make a dropdown box that displays 'Yes' and 'No' options? When 'Yes' is selected, how do I show another div on the page? ...

Error: The function exec in matchExpr[type] is not defined

I made some changes to Object.prototype and now I'm running into errors with jQuery's methods on selectors. The error message I'm getting is: Uncaught TypeError: matchExpr[type].exec is not a function Additionally, when trying to use $.po ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

Cookie Setting - Utilizing a jQuery Modal Box for Confirmation Messages

This unique jquery_modal_confirm_dialogue has been perfected through numerous experiments. When our site visitors agree to our Terms of Use, they are automatically directed to the product page products.html An essential feature I am in need of is setting ...

How does the functionality of $.ajax differ from that of $.get?

Similar Inquiry: Understanding the Variations of $.ajax(), $.get(), and $.load() I'm curious about the disparities between $.get() and $.ajax The given code showcases calls like this: $.get(href) .success(function (content) { $(&apos ...

Can you explain how to utilize theme values in CSS within Mui?

Working on my React app with mui themes, I have the following in index.js: let theme = createTheme({ palette: { primary: { main: "#00aaa0", contrastText: '#fcf4d9', }, secondary: { main: "#D55B3E&quo ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...