0

i have 'ul li', where is text, i want that when text in 'li' changes after click happen something, for example console.log. here is my code example:

html:

<ul>
<li>first</li>
</ul>

<button>click</button>

javascript:

document.queryselector('button').addEventListener('click', function(){
let list = document.queryselector('li');
let text = list.innerHTML = 'second';
if(list.changed){
  console.log(changed);
}
});
2
  • You are missing a ': let text = list.innerHTML = 'second'; Commented Sep 5, 2020 at 11:25
  • querySelector => S need to be capital. Also, i am not sure what is list.changed ? There is nothing like changed in Javascript - Can you add what are you trying to do ? Commented Sep 5, 2020 at 11:41

1 Answer 1

1

One way to do this is with a MutationObserver.

document.querySelector('button').addEventListener('click', function(){
  let list = document.querySelector('li');
  let text = list.innerHTML = 'second';
});

const observer = new MutationObserver(function(mutationsList, observer) {
  for(let mutation of mutationsList) {
    // This will handle changes to the innerHTML, though the check isn't 
    // really necessary since this is the only change we're observing
    if (mutation.type === 'childList') {
      console.log(mutation.target);
    }
  }
});

observer.observe(document.getElementById("testNode"),  { attributes: false, childList: true, subtree: false });
<ul>
<li id="testNode">first</li>
</ul>

<button>click</button>

MutationObserver reference

This is a general way to watch for changes, but depending on the end goal of watching for the change there may be better ways to handle this situation. For example, if you know that the only way you'll end up changing the element is through clicking the button, I'd recommend that you route all of your handling through the same place.

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.