UserTMP101010
UserTMP101010

Reputation: 113

Print content of element to console

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.

Example:

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

Console Output:

ID : ID5667

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

Upvotes: 9

Views: 46127

Answers (5)

Francisco Costa
Francisco Costa

Reputation: 7133

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);
}

Upvotes: 3

Para
Para

Reputation: 3711

Using 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())
    

Upvotes: 0

dReAmEr
dReAmEr

Reputation: 7196

I think below should work for you.

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

console.log(result);

For more reference : getElementByClassName

Upvotes: 18

boreq
boreq

Reputation: 840

Or if you want to use jQuery as a tag indicates you can do that using .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.

Upvotes: 0

Taylor Buchanan
Taylor Buchanan

Reputation: 4757

Pure JavaScript:

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

jQuery:

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

Upvotes: 0

Related Questions