0

I have a ul list inside which li is there, and inside li text and div are there. the same class is assigned to li while div is assigned with a different class name.

I just want to get the text from div and not from li.

Just need to get the "I need this text 112" from the div. I am trying:

li = ul.getElementsByTagName('li');
<ul class="category">
  <li class="hero" href="page1.htm">
    <a href="page1.htm"><img src="img/001.png" /></a>
    <div class="Hello">
      <a href="page1.htm">I need this text&nbsp;112</a>
    </div>
  </li>

But it gives me an error.

Andrew Bone
  • 7,092
  • 2
  • 18
  • 33
martel_9
  • 11
  • 1
  • 6
  • If you want text from a `div`, shouldn't your code refer to a `div`? If you want text, shouldn't your code say something about text? – Scott Hunter May 22 '18 at 11:36
  • Try it: var child = ul.children[0].children[1]; [Best way to get child nodes](https://stackoverflow.com/questions/10381296/best-way-to-get-child-nodes) – Quockhanh Pham May 22 '18 at 11:39
  • 1
    @QuockhanhPham `children` isn't the best way to get child *nodes*. It's the best way to get child *elements*. But the OP's starting point is the `ul`, the `a` isn't a child. You're missing at least one level in your example there, and doing things like chained `children` with hardcoded indexes is brittle. `querySelector`/`querySelectorAll` is almost always the better solution. – T.J. Crowder May 22 '18 at 11:41

2 Answers2

1

Use querySelector to find the element from the document or, if you already have a reference to the ul, you can use that as a starting point.

var elem = document.querySelector(".category li div.Hello a");
// or var elem = ul.querySelector("li div.Hello a")
alert(elem.textContent)
<ul class="category">
<li class="hero" href="page1.htm">
    <a href="page1.htm"><img src="img/001.png"></a>
    <div class="Hello">
        <a href="page1.htm">I need this text</a>
    </div>
</li>
</ul>
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You can use document.querySelector passing it a string containing any valid CSS selector, and it will return a reference to the first matching element. There's also Element#querySelector which does the same thing when your starting point is an element (as yours appears to be, your ul). Once you have the element, textContent is probably your best way to get the text now, although you could also use innerText on some browsers. (You can also use innerHTML — on any browser — if you want the HTML, not just the text.) So for instance:

text = ul.querySelector(".hello a").textContent;

If there may be multiple matches and you don't want the first, get a list from querySelectorAll (on document, on elements) instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875