如何使用id在类中添加新元素

时间:2019-04-17 08:40:45

标签: javascript

如何使用#id 32后版本在类中添加元素

<div id="post-32">
  <div></div>
  <div></div>
  <div class="post-card">
    <a href="#">01</a>
    <div>
      <h3 class="post-title">
        <!-- <h3 class="title">Discover Our </h3> -->new element should here
      </h3>
    </div>
  </div>
</div>

<script>
  var second_post = document.getElementById('post-32');

  var inner_child = second_post.getElementsByTagName('div')[2].childNodes[1];

  var title_scondPost = document.createElement('h3');

  title_scondPost.className = 'title';

  title_scondPost.append(document.createTextNode('Discover Our'));

  inner_child.append(title_scondPost);
</script>

2 个答案:

答案 0 :(得分:1)

尝试使用querySelector(),因为它可以像选择器一样使用CSS,因此很容易定位元素:

document.querySelector('#post-32 > .post-card > div > h3.post-title');

var inner_child = document.querySelector('#post-32 > .post-card > div > h3.post-title');
var title_scondPost = document.createElement('h3');
title_scondPost.className = 'title';
title_scondPost.append(document.createTextNode('Discover Our'));
inner_child.append(title_scondPost);
<div id="post-32">
  <div></div>
  <div></div>
  <div class="post-card">
    <a href="#">01</a>
    <div>
      <h3 class="post-title">
      </h3>
    </div>
  </div>
</div>

答案 1 :(得分:0)

您已经在DOM中添加了h3标签,无需创建新标签。

<div id="post-32">

<div></div>

<div></div>

<div class="post-card">

<a href="#">01</a>

<div>

<h3 class="post-title">

<!-- <h3 class="title">Discover Our </h3> --> new element should here

</h3>

</div>

</div>

</div>

<script>

  var second_post = document.getElementById('post-32');

  var inner_child = second_post.getElementsByTagName('div')[2].childNodes[1];

  var title_scondPost = document.getElementsByClassName('post-title')[0];

  title_scondPost.append(document.createTextNode('Discover Our'));

  inner_child.append(title_scondPost);

</script>