Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Parent Class

I am having a problem with my javascript that I can't quite explain. Here is the html:

<body>
<div id='slidecarousel' class='slide1' onclick='No functions can be here'>
<div id="sliderButton" onclick='pageSlider(this)'>Next Slide</div>
<div id='piece of slider...'></div>
<div...></div>
...
</div>
</body>

Here is the javascript and the error:

function pageSlider(elem)
{
    var pDiv = $(elem).parent('#slidecarousel')
    if ( pDiv.className.match(/(?:^|\s)slide1(?!\S)/) ){

**Uncaught TypeError: cannot call method 'match' of undefined**

         pDiv.className = "slide2";
    } else {
    pDiv.className = "SlideErr";
}
}

1 Answers

pDiv is a jQuery object, NOT a DOM element so it doesn't have a className property. You can get the first DOM element with:

pDiv[0]

So, just change this:

var pDiv = $(elem).parent('#slidecarousel')

to this:

var pDiv = $(elem).parent('#slidecarousel')[0];

As an additional change, this doesn't make a whole lot of sense:

var pDiv = $(elem).parent('#slidecarousel')

If you just want the #slidecarousel object, then just use:

var pDiv = $('#slidecarousel')[0];

because there can only be one #slidecarousel object in the whole page anyway.


Or, if you just want the parent of elem, then use this:

var pDiv = elem.parentNode;

Or, you could also use .closest() like this:

var pDiv = $(elem).closet(".slide1")[0];
like image 54
jfriend00 Avatar answered Mar 12 '26 09:03

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!