简体   繁体   English

如何在h3标签中查询内容

[英]How to query for the content inside a h3 tag

I am using the following jQuery code to try to get the text inside the element and add it to my variable: 我正在使用以下jQuery代码来尝试获取元素内的文本并将其添加到我的变量中:

   <script>
    var title = $('h3').html();
    alert(title);
   </script>

However, my browser is alerting me 'undefined' instead of the value inside the tag. 但是,我的浏览器警告我“未定义”,而不是标记内的值。 Any idea what I am doing wrong? 知道我在做什么错吗?

Here is the html section for reference: 这是供参考的html部分:

    <article>
      <div class="row">
        <div class="columns large-6 large-centered medium-8 medium-centered small-12">
          <h3>This is the post title</h3>
          <h4>written by <b>Myself</b></h4>
          <section>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lacinia urna sit amet convallis dictum. Curabitur non sodales orci. Praesent vel gravida felis. Cras ultricies velit mi, eget efficitur ipsum tempus nec.</p>
          </section>
        </div>
      </div>
    </article>

Thanks, 谢谢,

This is the solution using plain JavaScript; 这是使用普通JavaScript的解决方案。 you don't actually need jQuery here. 您实际上在这里不需要jQuery。

var h3element = document.getElementsByTagName("h3")[0];

This returns an array of all h3 elements in the document, of which you'll take the 0th index. 这将返回文档中所有h3元素的数组,其中的索引为0。 Then, simply access the innerHTML property: 然后,只需访问innerHTML属性:

var h3content = h3element.innerHTML;

A complete solution would look something like: 完整的解决方案如下所示:

<script>
    var title = document.getElementsByTagName("h3")[0].innerHTML;
    alert(title);
</script>

Try to wait for your document to trigger the ready event, if your code is beyond your tag, for example in the header. 如果您的代码超出了标记范围(例如在标头中),请尝试等待文档触发ready事件。 And if you only need the text, use the text function in jQuery. 如果只需要文本,请在jQuery中使用text函数。

<script>
  $(function() {
    var title = $('h3').text();
    alert(title);
  });
</script>

做类似的事情:

alert(document.getElementsByTagName('h3')[0].innerHTML)

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

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