循环getElementsByClassName()后获取innerHTML

时间:2015-10-30 06:04:10

标签: javascript

我的示例代码:

<?php
if( have_rows('p3projectsres') ):
    while ( have_rows('p3projectsres') ) : the_row(); ?>
         <div class="s3block">
        <p> <a href="<?php the_sub_field('p3projectreshires'); ?>" rel="lightbox" title="<?php the_sub_field('p3projectresdescription'); ?>">

                <!-- <div class="locationscript"><?php the_sub_field('p3projectreslocation'); ?></div> -->
                <div class="s3blockblurb">
                    <div class="scribe7">   
                        <?php the_sub_field('p3projectresblurb'); ?>
                    </div>

                    <div class="s3blockfaded"><?php the_sub_field('p3projectreslocation'); ?></div>

                </div>
                <img src="<?php the_sub_field('p3projectrespreview'); ?>" /> 
            </a></p>
        </div>
    <?php  endwhile;
else : endif;
?>

我的问题是:如何在类名中加入<!DOCTYPE html> <html> <body> <div class="names"> <i>Name 1.</i> </div> <div class="names"> <i>Name 2.</i> </div> <div class="names"> <i>Name 3.</i> </div> <input type="button" value="Change all names" onclick="changeNames()" /> <script> var changeNames = function() { var names = document.getElementsByClassName('names'); for (var i = 0; i < names.length; i++) { names.item(i).textContent = names.item(i).textContent + ' Changed...' } } </script> </body> </html> 标记?

<i>不包含names.item(i).textContent代码。

我已尝试过此操作,但它无效:<i>

并且names.item(i).find('i').textContent也不支持names.item(i)

2 个答案:

答案 0 :(得分:2)

使用 Element.querySelector() 在div中获取i标记。

var changeNames = function() {
  var names = document.getElementsByClassName('names');

  for (var i = 0; i < names.length; i++) {
    names.item(i).querySelector('i').textContent += ' Changed...'
      // or
      // names[i].querySelector('i').textContent += ' Changed...'
  }
}
<div class="names">
  <i>Name 1.</i>
</div>

<div class="names">
  <i>Name 2.</i>
</div>

<div class="names">
  <i>Name 3.</i>
</div>

<input type="button" value="Change all names" onclick="changeNames()" />

答案 1 :(得分:0)

因为这是html内容所以使用innerHTML

&#13;
&#13;
var changeNames = function() {
  var names = document.getElementsByClassName('names');

  for (var i = 0; i < names.length; i++) {
    names[i].innerHTML += ' Changed...';
    //another approach is to add a text node than to modify the html content like
    //names[i].appendChild(document.createTextNode(' Changed...'))
  }
}
&#13;
<div class="names">
  <i>Name 1.</i>
</div>

<div class="names">
  <i>Name 2.</i>
</div>

<div class="names">
  <i>Name 3.</i>
</div>

<input type="button" value="Change all names" onclick="changeNames()" />
&#13;
&#13;
&#13;