简体   繁体   中英

How to select first element that has content in JavaScript or CSS

Can anyone help me to select the first element that has content ie i want to select the </p> element with the textContent 'Lorem Ipsum Dolor Sit Amet' which is the first </p> element with content.

Code

<div class="container">

  <p class="empty-para"><p>
  <p class="empty-para-ii"><p>
  <p> Lorem Ipsum Dolor Sit Amet<p>
  <p> The quich brown fox jumped over the lazy dog.<p>

<div>

I need this answer to style the first </p> element(with content) with border

Try this solution using Javascript

 const container = document.querySelector("div.container"); // Get the parent element const elements = Array.from(container.children); // Transform to an array all container child elements const element = elements.find((element) => element.textContent); // Find the first element with content console.log(element);
 <div class="container"> <p class="empty-para"></p> <p></p> <p class="empty-para-ii"></p> <p></p> <p>Lorem Ipsum Dolor Sit Amet</p> <p></p> <p>The quich brown fox jumped over the lazy dog.</p> <p></p> </div>

See

First, CSS selector can be used to select all the non-empty children. And then simply use the zeroth element.

let nonEmptyChildren = document.querySelectorAll('.container > p:not(:empty)');
if (nonEmptyChildren.length) {
    nonEmptyChildren[0].style.color = 'green'; // do whatever you want to the zeroth element.
}

You can try this:

const ptags = document.querySelectorAll('p');   // select all p tag elements
  ptags.forEach((item) => {
    if(item.text) {. //check if they have any text
        // do something with item
    }
  });

first of all close your p tags like this:

<p> some content </p>

and i think you want this:

var tags = document.querySelectorAll('p');
var firstP = [] ;
tags.forEach(function(item){
 if(firstP.length > 0){
  return
 } 
 if(item.textContent){
  firstP.push(item);
  item.style.border = '1px solid red'
 } 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM