0

I have element as below:

<li class="someClass">value1<span>value2</span></li>

The above list element is generated through vanila js so the click event is bind to it as below:

const list = Array.from(document.querySelectorAll(".someClass"));
  list.forEach(ele => ele.addEventListener('click', this.getListValue.bind(this)));

getListValue(element)
{
 console.log('output', element.target.innerText)
}

In output I get on IE:

output value1 value2

chrome:

 output value1

I need only value1. Is there a way to get value of li tag for given scenario?

Thanks!

6
  • Why do you even want to read elements from your templates? Commented Sep 19, 2018 at 10:56
  • @Amadán I need value of element to do some further action. In my case li element is a dropdown for search input and when user click on an li (i.e one of the item from dropdown) I want to grab that value and show some results on next page. Commented Sep 19, 2018 at 11:00
  • 1
    If you using Angular(-JS), then use ng-model and not read any content from HTML. Commented Sep 19, 2018 at 11:00
  • @Justinas I am using Angular (5.2). and I can't add [(ngModel)] as creating multiple li using vanila js code. Commented Sep 19, 2018 at 11:01
  • @Simer why are you doing that? create multiple <li> using *ngFor! Commented Sep 20, 2018 at 6:42

1 Answer 1

1

You're adding elements to the DOM that you then want to read again using vanilla JS? I'm having some trouble understanding what this has to do with using Angular or not, and why you'd want this...

Angular explicitly discourages messing with the native elements yourself. Also, you already had the value when generating the element, why bother reading it again? If you're going to insist on this approach anyways, you might as well add the on click when generating your html, where you should already have value1.

Anyhow, assuming you really have a valid use case for your approach and aren't just glueing copy pasted code together while completely ignoring the Angular concept (or any concept really), have a look at: Is there a way to get innerText of only the top element (and ignore the child element's innerText)?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.