Home>

From HTML tagsgetElementsByClassNameI'm trying to store the values ​​I got using.

In particular

<li>apple</li>
<li>orange</li>
<li>melon</li>
<li>watermelon</li>

To

['apple','orange','melon','watermelon']


I want to do it.

Since I want to write the array to csv etc., I want to display it on the terminal (Mac) etc. like the command prompt (windows) etc.

Current output
On the browserelement.textContent + = elements [0] .outerHTML + "\ n";You can see that you can get the element using.

apple
orange
melon
watermelon

However, it can be expected that it will be difficult to store it in an array from this state and check it in the terminal in the HTML state, but I can not find what to do by searching, so I do not know how to approach it. I'm in trouble.

Corresponding source code

Document.getElementsByClassName ()-Get elements from class attributeI am changing a part of the tutorial of the article.

<! DOCTYPE html>
<html>
<head>
<style>
    div # result {white-space: pre-wrap;}
</style>
</head>
<body>
<ul>
  <li>apple</li>
  <li>orange</li>
  <li>melon</li>
  <li>watermelon</li>
</ul>
<hr>
<script>
var element = document.getElementById ("result");
var elements = document.getElementsByClassName ("hoge");
console.log (elements);
element.textContent = elements + "\ n \ n";
element.textContent + = elements [0] .outerHTML + "\ n";
element.textContent + = elements [1] .outerHTML + "\ n";
element.textContent + = elements [2] .outerHTML + "\ n";
element.textContent + = elements [3] .outerHTML + "\ n";
</script>
</body>
</html>
Supplementary information (FW/tool version, etc.)

Mac OS

  • Answer # 1

    I want to display it on the terminal (Mac), which is the same as the command prompt (windows).

    It is normal to operate the terminal on the OS side from JavaScript in the browser.can not..

    Either "Create CSV in the browser and copy/paste or download the file" or "Interpret HTML from a program running on the command line".

  • Answer # 2

    elements is an HTMLCollection, and we count it up and store it in an array.

    // Array to store
    var ar = [];
    for (var i = 0;i<elements.length;i ++) {
        // Store the text part
        ar.push (elements [i] .innerText);
    }
    // console.log (ar);

    Or with a relatively new writing style

    console.log (Array.from (elements) .map ((node) =>node.innerText));

    I think that you should convert it to Array and then process it with map etc.

    Did you understand that in the terminal you would get this out in console.log ()?

  • Answer # 3

    var res = [... document.getElementsByClassName ('hoge')]. map (x =>x.textContent);
    console.log (res);

Related articles

Related questions