Javascript 将元素的内容打印到控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28012614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:07:06  来源:igfitidea点击:

Print content of element to console

javascriptjqueryconsole

提问by UserTMP101010

I have a feed that is outputting content dynamically to an element. I want to take the text from element A and output it to the console log.

我有一个动态地将内容输出到元素的提要。我想从元素 A 中获取文本并将其输出到控制台日志。

Example:

例子:

<div class="elementa">ID5667</div>

Console Output:

控制台输出:

ID : ID5667

编号 : ID5667

I've tried a few things, but I'm either getting undefined or the full HTML of that element.

我已经尝试了一些东西,但我要么未定义,要么是该元素的完整 HTML。

回答by RE350

I think below should work for you.

我认为下面应该适合你。

var result = document.getElementsByClassName("elementa")[0].innerHTML;

console.log(result);

For more reference : getElementByClassName

更多参考:getElementByClassName

回答by Taylor Buchanan

Pure JavaScript:

纯 JavaScript:

console.log('ID : ' + document.getElementsByClassName('elementa')[0].innerHTML);

jQuery:

jQuery:

console.log('ID : ' + $('.elementa').text());

回答by Para

Using jQuery:

使用jQuery:

  • The .html()method gives you the HTML contents (see doc page). Use it as follows:

    console.log("ID: " + $("div.elementa").html())
    
  • If you just want the text contents, use the .text()method (see doc page):

    console.log("ID: " + $("div.elementa").text())
    
  • .html()方法为您提供 HTML 内容(请参阅文档页面)。使用方法如下:

    console.log("ID: " + $("div.elementa").html())
    
  • 如果您只想要文本内容,请使用该.text()方法(请参阅文档页面):

    console.log("ID: " + $("div.elementa").text())
    

回答by boreq

Or if you want to use jQuery as a tag indicates you can do that using .text():

或者,如果您想使用 jQuery 作为标记,则表明您可以使用以下方法.text()

console.log($('.elementa').text());

It is also possible to use .html()but the behavior will be different if the HTML tags are present inside that tag. Compare two documentations.

也可以使用,.html()但如果 HTML 标签存在于该标签内,则行为会有所不同。比较两个文档。

回答by Francisco Costa

If you are looking for the content of multiple classes you can do this:

如果您正在寻找多个类的内容,您可以这样做:

var elements = document.getElementsByClassName("className");

for (i = 0; i < elements.length; i++) {
    console.log(elements[i].innerHTML);
}