Noob5456 - 8 months ago 43
Javascript Question

# querySelector returning null when used in combination with "this"

I've been searching for a while now and haven't found a good answer as to why the querySelector is returning null.
The image it's using as a background will obviously not work from here, so I colored the boxes black so you could see them, I was able to get the spriteHover function to work but only for one li by replacing the var c = querySelector("li"); with var c = document.getElementById("social").children[1]; or 0 or whichever number you want to be functional.

ps: the first func works fine.

On this codepen you can see the querySelector working so I'm stumped.
http://codepen.io/anon/pen/doZbPQ?editors=101

function sprite() {

var c = document.getElementById("social").children;
var k = 0;
var cnc = "";
for (i = 0; i < c.length; i++) {
c[i].style.backgroundImage = "url(../Imgs/social_icons.jpg)";
cnc = String(k) + "px 0px";
k = k - 28;
c[i].style.backgroundPosition = cnc;
}
}

function spriteHover() {
var c = this.querySelector("li");
var pnc = "0px -29px";
c.style.backgroundPosition = pnc;
}
sprite();
alert("working");

.smedia {
background-color:;
height: 20px;
position: absolute;
}
.smedia > ul {
position: relative;
display: inline-block;
background-color:;
left: 836px;
height: 28px;
margin-right: 8px;
margin-top: 8px;
}

.smedia > ul li {
background-color: black;
display: inline-block;
height: 28px;
width: 28px;
}
.smedia a {
display: inline-block;
color: black;
text-decoration: none;
height: 28px;
width: 28px;
}

<nav class="smedia" id="smedia">
<ul id="social">
--><li><a href="https://www.instagram.com/?hl=en" class="ig" target="_blank"></a></li><!--
--><li><a href="https://www.tumblr.com/" class="t" target="_blank"></a></li><!--
</ul>
</nav>

var c = document.getElementById("social").children;


So you get the children of the element with the id social.

These children are <li> elements because that element is<ul id="social">

c[i].addEventListener("mouseenter", spriteHover);


Then you bind your event listener to those elements. So the event listener is bound to the the list items.

var c = this.querySelector("li");


So this is the list item, and querySelector searches for a descendant of the list item which is another list item.

<li><a href="https://www.facebook.com/" class="fb" target="_blank"></a></li>


… but the only descendant is an a element and so you get null.

You want this not this.querySelector("li");.