-1

I'm trying to create HTML elements usingn DOM. I need to pass the <li> element to the toogle method as follows:

<ul>
<li onclick="toogle(this)"><a>Some text</a></li>
</ul>

How can I do it?

Current code that doesn't work:

var li = document.createElement("li");                  
li.onclick = toogle(this);

1

4 Answers 4

3
var li = document.createElement("li");
li.onclick = function () { toogle(this); };
Sign up to request clarification or add additional context in comments.

1 Comment

I eventually got to this solution and I think it is the best. Thank you!
1

This:

li.onclick = toogle(this);

actually EXECUTES that toogle function, and assigns its return value to the onclick. If you want your function to be called AS the click handler, then it should be

li.onclick = toogle;

1 Comment

I'm trying to pass the element <li> as an argument to the toggle method. This does not work.
0

The Snippet below demonstrates how to pass an element that was clicked by using event.target. Details are commented in source.

SNIPPET

var li = document.createElement("li");

// Needs to be in DOM before you can click it
document.querySelector('ul').appendChild(li);

// Assigning class for testing
li.className = 'klass';

// Add click event for li
li.addEventListener('click', function(e) {

  // event.target is always the element that was clicked
  var tgt = e.target;

  // Verifying that the li was passed
  console.log(tgt.className);

  // klass
}, false);
li {
  background: #000;
}
<ul></ul>

Comments

0

You can do:

var li = document.createElement("li");
li.addEventListener('click', toogle);

Which will call toogle on click. This is the better way to do it.

and then you can get the element with:

function toogle(e) {
  // "e.target" will represent the element
}

Or if you want it your way then you can do:

var li = document.createElement("li");
li.onclick = toogle;

and then you get the element with:

function toogle() {
  // "this" will represent the element
}

3 Comments

Not useful. You just ignored that I need to pass the element itself as an argument.
If you use onclick then this will represent the element when the functions called and if you use addEventListener then you can you the passed on argument (let's call it e) to get the element e.target.
I've made a edit to my answer and added a example for how you can get the element.

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.