Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or 'danger'. The order is important here - alerts come first followed by dangers. However, both are optional and can be preceded by other paragraphs that don't fall into those categories.

<div class='text'>

<p>Some paragraph0</p>

<p class="alert">Alert</p>
<p>Some paragraph1</p>
<p>Some paragraph2</p>

<p class="danger">Danger</p>
<p>Some paragraph3</p>
<p>Some paragraph4</p>

</div>

The main issue is figuring out how to apply style changes to elements that come after paragraphs with either the alert or danger class. Ideally, we should be able to specify whether these changes should be applied before or after the designated paragraphs.

.alert{
   background: #FFFF00;
    font-weight: bold;
}

.danger{
    background: #F00;
    font-weight: bold;
}

Answer №1

To address the issue of multiple warnings or dangers, you can utilize the ~ selector in CSS to target elements that come after either a danger or alert element. This solution takes into consideration the assumptions made in your particular case. However, please note that using this logic may result in unexpected behavior if there are multiple instances of warnings or dangers.

div.text p.alert ~ p:not(.danger), div.text p.alert {
    background: #FFFF00;
}

div.text p.danger ~ p:not(.alert), div.text p.danger {
    background: #F00;
}

div.text p.alert{
    font-weight: bold;
}

div.text p.danger{
    font-weight: bold;
}

Answer №2

To select them specifically, do the following...

.alert p:not(:first-child) {color:orange;}

.danger p:not(:first-child) {color:purple;}

Answer №3

In the world of CSS, when you need to target all paragraphs following a danger or alert tag, look no further than the general sibling selector!

.danger ~ p, .alert ~ p { // selects all paragraphs after a danger or alert tag
    // insert your desired css rules here.
}

Answer №4

You have the ability to utilize `javascript` for this task. This method is effective in all scenarios.

This technique applies to elements with a class="text" that consist of one element with either class alert or class danger, or both.

If no elements possess class alert or class danger, then no action will be taken.

Below is the code: (execute the snippet)

Note: I am assigning an example class named specialClass to the targeted elements, and there are two buttons at the bottom to simulate adding styles before and after alert or danger.

function applyStyles(whenToStyle)
{
  // select all elements with class 'text'
  var elements = document.querySelectorAll('.text');
  
  // loop through all elements with class 'text'
  for(var i=0; i< elements.length; i++)
  {
    // set flags to false for new container of class 'text'
    var alertSeen = false;
    var dangerSeen = false;
    var hasAlert = false;
    var hasDanger = false;
    
    // fetch the children in order as they appear on the page
    var children = elements[i].children;
    
    // check if elements with class 'alert' or 'danger' exist
    if(elements[i].getElementsByClassName('alert').length > 0) hasAlert = true;
    if(elements[i].getElementsByClassName('danger').length > 0) hasDanger = true;
    
    // go through all children elements of the selected element
    for(var j=0; j< children.length; j++)
    {
      // if the classList doesn't contain 'alert' or 'danger'
      if(!children[j].classList.contains('alert') && !children[j].classList.contains('danger'))
      {
          if(whenToStyle == 'before')
          {
            if((!alertSeen && hasAlert) || (!dangerSeen && hasDanger))
            {
              children[j].classList.add('specialClass');
            }
          }
          else if(whenToStyle == 'after')
          {
            if((alertSeen && hasAlert) || (dangerSeen && hasDanger))
            {
              children[j].classList.add('specialClass');
            }
          }
      }
      else
      {
        // mark if we are on an element with class 'alert' or 'danger'
        if(children[j].classList.contains('alert')) alertSeen = true;
        else if(children[j].classList.contains('danger')) dangerSeen = true;
      }
    }
  }
}
.alert{
   background: #FFFF00;
    font-weight: bold;
}

.danger{
    background: #F00;
    font-weight: bold;
}

.specialClass
{
  background-color:#09f;
  color:#FFF;
  font-size:1.3em;
}
<div class='text'>

  <p>Some paragraph0</p>

  <p class="alert">Alert</p>
  <p>Some paragraph1</p>
  <p>Some paragraph2</p>

  <p class="danger">Danger</p>
  <p>Some paragraph3</p>
  <p>Some paragraph4</p>

</div>

<input type="button" value="click to apply before" onclick="applyStyles('before')" />
<input type="button" value="click to apply after" onclick="applyStyles('after')" />

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

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...

How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click eve ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

Using TypeScript with Angular, you can easily include parameters to HTML tags

I have an HTML element that looks like this: eventRender(info){ console.log(info.el); } This is the output I'm seeing: https://i.stack.imgur.com/G0hmw.png Now, I want to include these attributes: tooltip="Vivamus sagittis lacus vel augue ...

JS: Discovering an element's screen position consistently across various computers

I am currently working with a matrix of size 13 x 20, where each cell contains a number ranging from 0 to 300, representing different tiles to build a map. In addition, there is a "hero" character - a movable image. Pressing an arrow key will move the her ...

Engaging Interactive Image/Graphic with React and HTML

Just starting out with react/html and attempting to create an interactive Graphic/Image. My goal is to have a circle highlight in color when the mouse hovers over it, and change to a different color when clicked. Is this achievable? Any advice on how to ac ...

Can anyone provide assistance with understanding the background-size property?

I am struggling to resize the background image on my website, similar to the one on this website. No matter what I try with the position or background-size property, the image remains too large and does not adjust properly. Additionally, I need the image t ...

Unable to interact with a button through JavaScript using execute_script in Selenium

https://i.stack.imgur.com/hJmtK.png I am attempting to remove a cookies popup by accepting the cookies and clicking confirm. While I am able to click an input labeled "zgadzam się na", for some reason, clicking a button with the label "potwierdź" appears ...

Bootstrap for a more streamlined container

https://i.sstatic.net/fJ8nt.png My Bootstrap setup includes a container-fluid with multiple cards inside. I want to adjust the container layout to stack the cards more closely together in a vertical direction, instead of being displayed in a grid format. ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

Is there a way to use Media Queries to require CSS to load an image?

Here is the CSS code I am using: html { background: url(../img/header_mobile.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } /* Smal ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

Resolving VSCode WebViewPanel access issues through a corporate proxy

I am currently utilizing the "C4 DSL Extension" in VSCode to display previews of my architecture diagrams. These previews are generated through the WebviewPanel functionality. If you're interested, you can access the source code here: While everythin ...

Adjusting the document root in an Apache site's directory

I have been working on my portfolio website and I want to showcase some past projects. There is one particular website that I developed in the past which is no longer live, but I have an archived version of it. I would like to be able to view this old site ...

How to load an iframe only upon clicking on a link

I am struggling to make the iframe popup appear only when a specific class link is clicked. Here is my HTML and JS code: Unfortunately, nothing happens when I click the link with the class 'aclass'. I have updated my JavaScript, but the issue ...

Retrieving image source from JSON data using AngularJS

I am attempting to retrieve an image from an API using AngularJS. The approach I'm taking involves triggering the $http function with a link and attempting to extract the image URL from the JSON response to display it in the HTML. However, despite re ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

What is the best way to ensure that my theme button changer has an impact on all pages throughout my website, not only on the

Looking for some help here - I've got a button that changes the theme/colour of my website, but it only seems to work on the homepage and not on any other pages. Anyone know how I can fix this issue? Here's the JavaScript code: $(document).ready ...

Toggle the class to slide in or out of the div

I am attempting to create a header with two positions - one absolute and one fixed. I want the header to smoothly slide in as you scroll down, and then slide out when you scroll back to the top. However, I am having trouble getting it to slide; instead, it ...