简体   繁体   中英

How to use javascript function on dynamically created element?

I created an li using

  static make(string, el) {
    var wrapper= document.createElement((el || 'div'));
    wrapper.innerHTML = string;
    return wrapper.firstChild;
  }

  static makeLi(string) {
    return this.make(string, "ul");
  }

This is the template for the string I'm passing in:

return `
  <li class="truer-companion">
    <a class="truer-companion-link" href="${url}">${this.escapeHTML(title)}</a>
    ${Vote.form_container(article_id)}
  </li>
`;

Where it is passed to a function with this

  static createVoteForms(el) {
    console.log(el);
    let foo = (el || document).getElementsByClassName("bar");

Which throws the error

Error in event handler for (unknown): TypeError: (el || document).getElementsByClassName is not a function

But somewhere else where I don't run createVoteForms with an argument it works fine.

And when I log el the output is #text but has attributes like an object.

And when I log el the output is #text but has attributes like an object.

A DOM has lots of different kinds of nodes.

When you call createElement , you create an element node .

The value you are passing to createVoteForms is a text node . This is how text is represented in a DOM. (It wouldn't do much good if you could have a <p> but had no way of putting text inside it!).

Text nodes do not have a getElementsByClassName method (because text nodes cannot contain other nodes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM