【问题标题】:How to select first element that has content in JavaScript or CSS如何选择第一个包含 JavaScript 或 CSS 内容的元素
【发布时间】:2020-10-25 11:02:56
【问题描述】:

谁能帮我选择第一个有内容的元素,即我想选择 </p> 元素与 textContent 'Lorem Ipsum Dolor Sit Amet' 这是第一个带有内容的</p> 元素。

代码

<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>

我需要这个答案来设置带有边框的第一个 &lt;/p&gt; 元素(带有内容)

【问题讨论】:

  • 嘿,谢谢你的问题。你都尝试了些什么?你看过Element.innerHTML吗?

标签: javascript css


【解决方案1】:

首先,CSS 选择器可用于选择所有非空子项。然后简单地使用第零个元素。

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

【讨论】:

    【解决方案2】:

    首先像这样关闭你的 p 标签:

    <p> some content </p>
    

    我想你想要这个:

    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'
     } 
    })
    

    【讨论】:

      【解决方案3】:

      使用 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>

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        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
            }
          });
        

        【讨论】:

        • 嗨 Tushar,感谢您的回答,但实际上我需要的是选择第一个带有内容的 &lt;p&gt; 元素
        • 当到达p标签的内容为The quich brown fox jumped over the lazy dog.时,条件也将被满足
        猜你喜欢
        • 2015-12-06
        • 2012-01-25
        • 2023-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-03
        • 2016-03-06
        • 1970-01-01
        相关资源
        最近更新 更多