简体   繁体   English

如何使用 div 内的内容定位 div

[英]How to target a div using content inside the div

I have 2 divs with same class name but different strings inside the div.我有 2 个具有相同 class 名称的 div,但 div 内的字符串不同。 I want to use an insertAfter the first div to display some additional text, but the text is being displayed under both divs:我想在第一个 div 之后使用 insertAfter 来显示一些额外的文本,但是这些文本都显示在两个 div 下:

<div class='test'>First Div</div>
<div class='test'>Second Div</div>

My approach:我的做法:


if ( document.getElementsByClassName('test')[0] 
  && document.getElementsByClassName('test')[0].innerHTML == 'First Div'
   ) {
     $('<h2>Inserting New Text</h2>').insertAfter('.test')[0];
   }

But this adds the text after both the First Div and the Second Div.但这会在 First Div 和 Second Div 之后添加文本。 I want to know if there is a way to insert only once or insert after matching the string我想知道是否有办法只插入一次或匹配字符串后插入

Just keep it simple, find all elements with target class and pick the first one:保持简单,找到目标为 class 的所有元素并选择第一个:

 const el = document.getElementsByClassName('test') $('<div>new text</div>').insertAfter(el[0])
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'>First Div</div> <div class='test'>Second Div</div>

You can ask javascript to find the elements of the class and then convert the result into an array and find the first element that matches your condition.您可以要求 javascript 查找 class 的元素,然后将结果转换为数组并找到与您的条件匹配的第一个元素。

 const elements = Array.from(document.getElementsByClassName("test")); const target = elements.find(el => el.innerHTML === 'First Div'); $('<h2>Inserting New Text</h2>').insertAfter(target);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='test'>First Div</div> <div class='test'>Second Div</div>

No need for jQuery here.这里不需要 jQuery。 Use insertAdjacentHTML to add the new element.使用insertAdjacentHTML添加新元素。

 // Pick up the first element with the test class const el = document.querySelector('.test'); // Use `insertAdjacentHTML` to add the new div after it el.insertAdjacentHTML('afterend', '<div>new text</div>');
 <div class="test">First Div</div> <div class="test">Second Div</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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