$(this) children always returns undefined

- 1 answer

Ad

I have problem with undefined being returned by innerHTML. Maybe it is because of a difference between html() and innerHTML?

My JavaScript code:

var content2 = document.getElementById("content2");
var opis;

$(function() {
  $('.blok').click(function(e) {
    opis = $(this).next('.opis');
    if (!$('.popup:visible').length) {
        content2.innerHTML= opis.html();
        $('.popup').fadeIn();
    }
    e.preventDefault();
    return false;
  });

  $('.popup .close, .popup .bg').click(function() {
    $(this).parents('.popup').fadeOut();
  });
})

My HTML:

<body oncontextmenu="return false" onselectstart="return false" onselect="return false" oncopy="return false">
    <div class="popup"> 
        <div class="bg"></div> 
        <div class="container"> 
            <div id="content2"> </div> 
        </div> 
    </div> 
    And example of "blok": 
    <div class="blok"> $$|DO| = |OC| = 5$$ <div class="opis">2</div>
</div>

Why does content2 always return undefined?

Ad

Answer

Ad

Element with class blok and opis are not on the same level in the DOM structure. So $(this).next('.opis') is invalid. jquerynext() is used when the elements are on the same DOM level. You need the following expression to get to the right element. opis is actually a child of block

 $('.blok').click(function(e) {
    opis = $(this).find('.opis');

Example : https://jsfiddle.net/DinoMyte/pmnsvzrr/5/

OR

$('.blok').click(function(e) {
$(this).children('.opis');

Example : https://jsfiddle.net/DinoMyte/pmnsvzrr/4/

Ad
source: stackoverflow.com
Ad