88

in the process of learning javscript and jquery, went through pages of google but can't seem to get this working. Basically I'm trying to collect innerhtml of classes, jquery seems to be suggested than plain javascript, into a document.write.

Here's the code so far;

<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>

<script>
var mvar = $('.mbox').html();
document.write(mvar);
</script>

With this, only the first class shows under document.write. How can I show it all together like Block OneBlock TwoBlock Three? My ultimate goal with this is to show them comma seperated like Block One, Block Two, Block Three, Block Four. Thanks, bunch of relevant questions come up but none seem to be this simple.

Arash Milani
  • 6,149
  • 2
  • 41
  • 47
Jake
  • 1,047
  • 3
  • 11
  • 13

5 Answers5

109

One possible way is to use .map() method:

var all = $(".mbox").map(function() {
    return this.innerHTML;
}).get();

console.log(all.join());

DEMO: http://jsfiddle.net/Y4bHh/

N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 1
    This definitely works, but what is the use of the "get()" function call after map() ? – roneo May 13 '20 at 17:35
  • @roneo It returns a plain JS array and not array-like object, that jQuery returns from `map`. – VisioN May 14 '20 at 09:15
  • Can you elaborate? I tried to search for an answer but could not find a satisfying one. What is array-like object? Does the "get()" function apply to each iteration? – roneo May 14 '20 at 12:50
  • 1
    @roneo Check it yourself: http://jsfiddle.net/b5vpmyh4/. Otherwise, [jQuery docs say it explicitly](https://api.jquery.com/map/): *As the return value is a jQuery object, which contains an array, it's very common to call `.get()` on the result to work with a basic array.* – VisioN May 15 '20 at 12:56
  • Thanks mate! Good explanation – roneo May 19 '20 at 17:20
  • @VisioN what is `this` here? Can you please rewrite this as an arrow function? I tried `var all =$('h3').map(i=>i.innerHTML).get()`, and it didn't work. – Andrew Anderson Oct 01 '21 at 21:44
  • 1
    @AndrewAnderson `this` refers to the current DOM element for each iteration. The arrow function does not keep the binding context, so `this` is not available there. You can use the [second callback parameter](https://api.jquery.com/map/) instead: `var all = $('h3').map((_, element) => element.innerHTML).get()`. – VisioN Oct 04 '21 at 13:26
  • To retrieve the object, just use `return this` instead of `return this.innerHTML` – S. Dre Feb 10 '22 at 10:51
79

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);
kufudo
  • 2,803
  • 17
  • 19
8

With the code in the question, you're only directly interacting with the first of the four entries returned by that selector.

Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/

I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
    </head>

    <body>
        <div class="mbox">Block One</div>
        <div class="mbox">Block Two</div>
        <div class="mbox">Block Three</div>
        <div class="mbox">Block Four</div>

        <div id="outige"></div>
        <script>
            // using the $ prefix to use the "jQuery wrapped var" convention
            var i, $mvar = $('.mbox');

            // convenience method to display unprocessed html on the same page
            function logit( string )
            {
                var text = document.createTextNode( string );
                $('#outige').append(text);
                $('#outige').append("<br>");
            }

            logit($mvar.length);

            for (i=0; i<$mvar.length; i++)    {
                logit($mvar.eq(i).html());
            }
        </script>
    </body>

</html>

Output from logit calls (after the initial four div's display):

4
Block One
Block Two
Block Three
Block Four
ruffin
  • 16,507
  • 9
  • 88
  • 138
2

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);
Sam
  • 2,950
  • 1
  • 18
  • 26
1

to get the input value you can do something like this:

 var allvendorsList = $('.vendors').map(function () {
            return this.value;
        }).get();
Ch Usman
  • 519
  • 6
  • 9