Mathematics
Mathematics

Reputation: 7628

Getting all inner text of divs with same class

Is there way I can all inner html of all div with class="company Name".

Please guide me in right direction.

Edit

Can I use this in chrome console to get information out of a web page ?

Upvotes: 2

Views: 9524

Answers (5)

Grant Miller
Grant Miller

Reputation: 29047

You can obtain an array of innerText from elements containing class="company Name" using the following method:

Array.from(document.getElementsByClassName('company Name'), e => e.innerText)

Upvotes: 2

MT0
MT0

Reputation: 168406

JSFIDDLE

OPTION 1 - A one-liner

var innerHTMLs = Array.prototype.slice.call( document.getElementsByClassName( 'company_name' ) ).map( function( x ){ return x.innerHTML } );

console.log( innerHTMLs );

OPTION 2 - Slightly more verbose.

var elements = document.getElementsByClassName( 'company_name' ),
    innerHTMLs = [];
for ( var i = 0; i < elements.length; ++i )
    innerHTMLs.push( elements[i].innerHTML );
console.log( innerHTMLs );

OPTION 3 - Should work on older browsers (IE8 and earlier) too.

var innerHTMLs = [],
    elements   = document.getElementsByTagName( '*' ),
    classToMatch = 'bob';

for ( var i = 0; i < elements.length; ++i )
{
    if ( ( ' ' + elements[i].className + ' ' ).indexOf( ' ' + classToMatch + ' ' ) != -1 )
        innerHTMLs.push( elements[i].innerHTML );
}

console.log( innerHTMLs );

Upvotes: 7

Stefano Ortisi
Stefano Ortisi

Reputation: 5336

You could store all the strings in an array using jQuery:

var strings = [];

$('.yourclass').each(function(){
   strings.push( $(this).text() );
});

Upvotes: 1

user622327
user622327

Reputation:

You'd probably want to start with this:

var elements = document.getElementsByClassName('company name');

Then elements will be an array of all your divs. After than iterate through them using a 'for in' and pull out the inner html for each one. Maybe something like this:

var allInnerHTML = '';

for (index in elements)
{
    var element = elements[index];

    allInnerHTML = allInnerHTML + element.innerHTML;
}

Not sure exactly what you're wanting to do but hopefully this will help.

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22415

Please don't use jquery for this. It's very easy with plain ol' javascript.

var x = document.querySelectorAll("[class='company Name']");
for (var i=0;i<x.length;i++) {
    //grab x[i].innerHTML (or textContent or innerText)
}

Upvotes: 6

Related Questions