简体   繁体   中英

style.display of undefined while the element is properly defined

JSFiddle Demo

function toggleFoo() {
    var btn = $('button');

    btn.click(function () {
        var thisElem = $(this).closest('.parent').find('.children');
        console.log(thisElem.length)
        thisElem.style.display = (thisElem.style.display == 'none') ? 'block' : 'none';
    });
};

$(document).ready(function() {
    toggleFoo();
});

Why am I getting undefined when trying to access style.display of the element that is defined properly and which length can be accessed?

thisElem is a jQuery object , not a dom element reference so it doesn't have style property.

If you just want to toggle the display of the element, then you can simply use .toggle() method from jQuery.

 function toggleFoo() { var btn = $('button'); btn.click(function() { var thisElem = $(this).closest('.parent').find('.children'); console.log(thisElem.length) thisElem.toggle(); }); }; $(document).ready(toggleFoo); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="parent"> <button>Click me</button> <div class="children"> <h2>foo</h2> </div> </div> 

If you want to access the dom element, then you can say

var thisElem = $(this).closest('.parent').find('.children')[0];

please try this for your output :

function toggleFoo() {
    var btn = $('button');

    btn.click(function () {
        var thisElem = $(this).closest('.parent').find('.children');
        var display = (thisElem.css("display") == 'none') ? 'block' : 'none';
        thisElem.css("display",display);
    });
};

$(document).ready(function() {
    toggleFoo();
});

You need to access the dom to get the style property.

When you used $(this).closest('.parent').find('.children'); the result is wrapped in a jQuery object. To get the dom element you add the key index of the element you are targetting. eg [0] in your case.

Hence:

var thisElem = $(this).closest('.parent').find('.children')[0];

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