使用多个块在页面加载时向类中的第一个元素添加文本

时间:2018-06-03 14:54:29

标签: javascript jquery

重点是: 通过Javascript或JQuery查找仅第一个元素,其中包含" analytics"在 div class=""内,并在开头添加文本到此分析。此脚本必须适用于页面加载。

看起来如何

<div id="block_browsing_1" class="analytics">
  //content
</div>

<div id="block_browsing_2" class="analytics">
  //content
</div>

<div id="block_instagram_followers_1" class="analytics">
  //content
</div>

<div id="block_instagram_followers_1" class="analytics">
  //content
</div>

应该如何看待:

<div id="block_browsing_1" class="test analytics">
  //content
</div>

<div id="block_browsing_2" class="analytics">
  //content
</div>

<div id="block_instagram_followers_1" class="analytics">
  //content
</div>

<div id="block_instagram_followers_2" class="analytics">
  //content
</div>

5 个答案:

答案 0 :(得分:0)

您可以使用CSS选择器first-of-type

$('.analytics:first-of-type').addClass('test');

答案 1 :(得分:0)

&#13;
&#13;
document.querySelectorAll(".analytics")[0].classList.add("test");
&#13;
<div id="block_browsing_1" class="analytics">
  //content
</div>

<div id="block_browsing_2" class="analytics">
  //content
</div>

<div id="block_instagram_followers_1" class="analytics">
  //content
</div>

<div id="block_instagram_followers_2" class="analytics">
  //content
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

简单的纯JavaScript解决方案:

document.querySelectorAll(".analytics")[0].classList.add("test");

答案 3 :(得分:0)

你可以这样做:

$(document).ready(function() {
  var currentClass = $('.analytics').first().attr('class');
  $('.analytics').first().attr('class', 'test ' + currentClass);
});

'test'是您要在开头添加的文字

答案 4 :(得分:-1)

Google首先发生了什么?

jQuery(function($){ // act upon document ready event.
  $('.analytics').first().addClass('test');
});