-2

I am new in JavaScript and i run into a lot of problems, most of them I already found a solution, but there is a problem that I don't know how to fix it, it might seem sample but I struggled a lot with this problem and didn't found an answer.

So lets say that I have a <ul> like the given one:

<ul>
  <li>my content 1</li>
  <li>my content 2</li>
  <li>my content 3</li>
</ul>

How am I supposed to get the content from that <li> to use it in my code?

Master Red
  • 31
  • 2

3 Answers3

1

I think there's already an answer for your struggle: Get content of a DIV using JavaScript

In your case something like this would do:

var list = document.getElementsByTagName("UL")[0];

var content = list.getElementsByTagName("LI")[0].innerHTML;

Notice the [0] - that would select the first item. If you want the content from the second or third you will need to change it to [1] or [2]

Beni Sinca
  • 378
  • 4
  • 15
0

with getElementsByTagName

function example1() {
        let list = document.getElementsByTagName("li")
        Array.prototype.forEach.call(list, (item)=>console.log(item.innerHTML));
    }

with querySelectorAll

  function example2() {
        document.querySelectorAll('li')
            .forEach((li) => {
                console.log(li.innerHTML)
            });
    }

[Es6] convert an HtmlCollection to an Array with spread

function example3() {
    let elements = document.getElementsByTagName("li");
    let list = [...elements]
    //use with forEach
    list.forEach(item=>{console.log(item.innerHTML)})
    // or use direct
    console.log(list[0].innerHTML)
}
Reza Mazarlou
  • 2,986
  • 4
  • 22
  • 31
0

You can select the li(s) like so

 var li= document.querySelector('li');

then grab the text content from the li

 var liContent = li.textContent;
 console.log(liContent);

same thing but for a list of li

initializing an empty array

var listItemsContent = [];
    
document.querySelectorAll('ul li').forEach((li) => {
     //pushing into the empty array
     listItemsContent.push(li.textContent);
     console.log(li.textContent)
});

console.log(listItemsContent);
<ul>
  <li>my content 1</li>
  <li>my content 2</li>
  <li>my content 3</li>
</ul>
    
Not A Bot
  • 2,474
  • 2
  • 16
  • 33