I want to insert a comment element where half of all elements with a specific class designation appear.

Asked 2 years ago, Updated 2 years ago, 22 views

<div class="article_content">
</div>
<div class="article_content">
</div>
<div class="article_content">
</div>
<div class="article_content">
</div>

If there is an html like the one above, count the number of div tags with the class article_content and
I'd like to insert <!--Comment out--> in half that number (if 11, then 6). How can I achieve this?

I would appreciate it if you could let me know the details.

Thank you for your cooperation.

The above results are as follows:

<div class="article_content">
</div>
<div class="article_content">
</div>
<!--Comment out-->
<div class="article_content">
</div>
<div class="article_content">
</div>

javascript

2022-09-29 22:05

1 Answers

The following feeling in javascript

vardivs= document.getElementsByClassName("article_content"); // Node List
varlen=divs.length; // Number of elements
if(len%2)
    ++len; // odd +1
len/=2;//0 origin
var commentNode = document.createComment("Comment Out"; // Create Comment Node
document.body.insertBefore (commentNode, divs[len]); // Inserts before the element you specify.document.body is the parent element in this case.


2022-09-29 22:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.