user2986966 user2986966 - 1 year ago 34
Javascript Question

Javascript hiding objects in loop

Please help me. I want to hide ext by clicking on link, but something is wrong

But I could write only this, and don't undertand why it's not working! Maybe there is another way to do it? It's every time fills the same function. to li1 li2func, therefore thereis li1
Link to jsfiddler

html:`

<div>

<div class="left">
<ul>
<li><a id="11" href="#">one</a></li>
<li><a id="12" href="#">two</a></li>
<li><a id="13" href="#">three</a></li>
</ul>

</div>
<div class="right">
<p id="1">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque, qui.
</p>
<p id="2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus reiciendis veritatis voluptatibus optio explicabo? Dignissimos ex amet mollitia doloribus a.
</p>
<p id="3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit porro quisquam harum nemo, vitae itaque.</p>
</div>

</div>`


JS code:

var el = document.getElementsByTagName("p");
var cs = document.getElementsByTagName("a");
if(el) {
for (i = 0; i < el.length; i++) {
td = cs[i];
(function (_td) {
td.addEventListener('click', function(){
console.log(_td);
console.log(i);
document.getElementsByTagName("div")[i].className += document.getElementsByTagName("div")[i].className ? ' invis' : 'invis';
});
})(td);

Answer Source

You have a few problems with your javascript. You should have noticed this error in your javascript console: "Uncaught TypeError: Cannot read property 'className' of undefined", which might have led you to discover that document.getElementsByTagName("div") is not the selector you should be using. You did the work to produce an array of p tags (inexplicably named el), but then didn't make any reference to that within the closure you built.

Here's one way to fix that problem: give your closure a second argument, and pass the p tag of the corresponding number (i) to the a tag to which you're binding the click handler. Then modify the className string of that element.

var el = document.getElementsByTagName("p");
var cs = document.getElementsByTagName("a");

if(el) {
    for (i = 0; i < el.length; i++) {
         td = cs[i];
         ptag = el[i];
          (function (_td,_el) {
        td.addEventListener('click', function(){
            console.log(_td);
             console.log(i);
             _el.className += _el.className ? ' invis' : 'invis';
        });
    })(td,ptag);
    }
}

One other thing: you'll notice that console.log(i) always produces 3 because that i is not bound to the scope of the click handler, but rather the outer scope of the for loop, so when the user clicks on one of the a tags, the loop has already completed and i will always equal 3.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download