Artimal
Artimal

Reputation: 661

$(this) children always returns undefined

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?

Upvotes: 1

Views: 1154

Answers (1)

DinoMyte
DinoMyte

Reputation: 8858

Element with class blok and opis are not on the same level in the DOM structure. So $(this).next('.opis') is invalid. jquery next() 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/

Upvotes: 1

Related Questions