How to write a document.querySelector for the following code - javascript

I'm having difficulty writing the document.querySelector for the following code. Currently I've written this code as querySelector but it does not encompass everything...
Please help me improve this, thank you.
Edit: as there seemed to be some confusion, let me elaborate. I would like all the elements, from div, a, img, everything to be encompassed in the querySelector.
var areaa = document.querySelector("#menu #envelope #links");
<div id="menu">Click here to browse the internet.
<div id="envelope">
<div id="links" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
Edit 2 - as more code was required (the href elements are removed / added as needed)...
var menu = document.getElementById("menu");
var areaa = document.querySelectorAll(".areaa");
menu.addEventListener("mouseenter", addHref);
//areaa.addEventListener("mouseleave", remHref);
document.addEventListener("mousemove", function(){
if(this != areaa){
remHref();
}
});
menu.addEventListener("click", addHref);
document.addEventListener("click", function (){
if (this != areaa){
remHref();
}
});
var g = document.getElementById("g");
var s = document.getElementById("s");
function remHref (){
if (g.hasAttribute("href")){
g.removeAttribute("href");
}
if (s.hasAttribute("href")){
s.removeAttribute("href");
}
}
function addHref (){
setTimeout(activate, 250);
}
function activate (){
document.getElementById("g").setAttribute("href", "https://www.google.com");
document.getElementById("s").setAttribute("href", "https://www.example.com");
}

you might want to add a class to all elements you want to be captured, then use document.querySelectorAll
var areaa = document.querySelectorAll(".my-class");
html shoud look like this:
<div id="menu" class="my-class">Click here to browse the internet.
<div id="envelope" class="my-class">
<div id="links" class="my-class">
<div>
<a id="g" class="redirect">
<img class="my-class" id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>

If you want to select everything you can use the below:
var areaa = document.querySelectorAll("#menu #envelope #links *");
If you want to be more specific you can do the following (the code below will select all of the anchor tags and images inside #links):
var areaa = document.querySelectorAll("#menu #envelope #links a, #menu #envelope #links img");

You can use querySelectorAll
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Learn more: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use it like this:
var areaa = document.querySelectorAll('*');
This will return all items.
You can replace document with the container if you want to restrict this to a specific div.

2 things, either add a class to every div
<div id="menu" class="area">Click here to browse the internet.
<div id="envelope" class="area">
<div id="links" class="area" >
<div>
<a id="g" class="redirect">
<img id="google" src="assets/google.png" />
</a>
</div>
<div style="width: 20%;"></div>
<div>
<a id="s" class="redirect">
<img id="sava" src="assets/Logo_Sava.png"/>
</a>
</div>
</div>
</div>
</div>
and select all divs by
let areaa = getElementsByClassName("area");
or you can use document.querySelectorAll("yourclassname") to access all divs of that class name

Related

Not able to change nested div in javascript dom

I am new to javascript and I am facing problems in dynamically changing the onclick attribute of the anchor tag in html. Below is my code:
function changeImage(){
var charAll = <?php echo json_encode($_SESSION['char_all']); ?>;
var charCount = 0;
for (var key in charAll) {
var charDiv = document.getElementById(key);
var anchorTag = charDiv.getElementsByTagName('a')[0];
anchorTag.onclick = function(){startChar('1', charAll[key].toString());};
}
}
<ul id="portfolio-list" data-animated="fadeIn">
<li id="character1">
<img src="character1.jpg" width="250px" height="280px" alt="" />
<div class="portfolio-item-content">
<span class="header">Play!</span>
<p class="body"></p>
</div>
<i class="more">></i>
<div class="post-info">
<div class="post-basic-info">
<h3 class="text-center">Character 1</h3>
</div>
</div>
</li>
<li id="character2">
<img src="character2.jpg" width="250px" height="280px" alt="" />
<div class="portfolio-item-content">
<span class="header">Play!</span>
<p class="body"></p>
</div>
<i class="more">></i>
<div class="post-info">
<div class="post-basic-info">
<h3 class="text-center">Character 2</h3>
</div>
</div>
</li>
</ul>
What I intend on doing is to change the onclick function of each of the <li> elements. The session variable $_SESSION['char_all'] is a dictionary in php, where the key is the character name (string) and the value is the character id corresponding to the character name in my database table. So, ideally the <a> tags under the <li> tags should get the onclick attribute of startChar('1', '1') (for character 1) and startChar('1', '2') (for character 2). But, what I end up with is startChar('1', '2') for both the characters.
Where am I going wrong? It might be something very silly that I am overlooking. But, I am not able to figure out. So, please help me out!
Your for in procedure referes to key which changes while iterating thorugh charAll.
As a solution (not tested), you might want to wrap the function in an outer anonymous-function and pass key to it:
(function(currentKey) {
anchorTag.onclick = function(){startChar('1', charAll[currentKey].toString());};
})(key);

Targeting specific div to update image

I am using a simple piece of JS to change the image that is in a div from plus to minus. I have multiple divs on this page which are generated dynamically. How could I specifically change the sign on the div that is clicked. Currently I have the same class for each div. This means whenever I click any div only the first divs image changes, not the div that was clicked.
<div class="hover2 opacity" onclick="changeImage()">
<h3><a>Test</a></h3>
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
<br>
</div>
<div class="hover2 opacity" onclick="changeImage()">
<h3><a>Test</a></h3>
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
<br>
</div>
JS
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("plus")) {
image.src = "img/minus.svg";
} else {
image.src = "img/plus.svg";
}
}
Is the only way to fix this dynamically assigning new class to each div and generating multiple scripts for teach class?
EDIT:
I am using the same method as before but on a slightly different layout. Any reason why this isnt working?
<div class="open-link" style="display: block;">
<a href="#" class="img-change">
<p class="inner">Expand <br><img id="myImage" src="img/arrow-down.svg" width="20" height="20"></p>
</a>
</div>
JS
$(document).on('click','a.img-change',function(){
var $img = $(this).find('p.inner');
if($img.attr('src').match("down"))
$img.attr('src','img/arrow-up.svg');
else
$img.attr('src','img/arrow-down.svg')
});
Every img in your markup has the same id, this is bad, all elements, if they have an id, should be unique. This does NOT mean you should use a unique id on every image and a specific script for every button! That would be bad. Just remove the duplicate id's!
Then this is pretty easy, use jQuery to attach a click event to every div and look for the image within it
take off the in-line onclick
<div class="hover2 opacity">
and use jQuery
$(document).on('click','div.hover2',function(){
var $img = $(this).find('p.heading img');
if($img.attr('src').match("plus"))
$img.attr('src','img/minus.svg');
else
$img.attr('src','img/plus.svg')
});
You don't need to assign an id to the <img/> elements
HTML
<div class="hover2 opacity" onclick="changeImage(this)">
<h3><a>Test</a></h3>
<div class="layer1">
<p class="heading">view
<span class="s-right">
<img src="img/plus.svg" width="20" height="20">
</span>
<br>more</p>
<div class="content">hello</div>
</div>
<br>
</div>
JS
function changeImage(el){
var img = el.querySelector('span > img');
img.src = (img.src.match("plus")) ? "img/minus.svg" : "img/plus.svg";
}
You can try this:
$(document).ready(function() {
$(".opacity").on("click", function() {
var source = $(this).find("img").attr("src"); // Gives source of image inside the presently clicked div
console.log(source);
if (source.match("plus")) {
console.log("match");
$(this).find("img").attr("src", "img/minus.svg");
} else {
$(this).find("img").attr("src", "img/plus.svg");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="hover2 opacity">
<h3><a>Test</a></h3>
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
<br>
</div>
<div class="hover2 opacity">
<h3><a>Test</a></h3>
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
<br>
</div>
U still can use $(this).find('img') to find img for selected div and change the src.
Example
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage1" class="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
<div class="layer1">
<p class="heading">view <span class="s-right"><img id="myImage2" class="myImage" src="img/plus.svg" width="20" height="20"></span>
<br>more</p>
<div class="content">hello</div>
</div>
So it your javascript, u can use this
$(document).on('click','div.hover2',function(){
$(this).find('img').attr("src","img/minus.svg");
}
Jsfiddle link -> https://jsfiddle.net/w1yb5fcc/1/

DOM traversing using jQuery

I am trying to create a comparison overlay that shows items selected by users when they 'add to compare' link.(like one in flipkart that appears on top when you hit add to compare). Here is my code:
<div class="college-list-container">
<div class = "individual-college-container" id="text1">
<div class="image-header"><h3>text1</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison" id="comparison">Add to compare</div>
</div></a>
</div>
</div>
<div class = "individual-college-container">
<div class="image-header"><h3>text2</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison">Add to compare</div>
</div></a>
</div>
</div>
<div class = "individual-college-container" id="itm">
<div class="image-header" ><h3>text3</h3>
</div>
<div class="dark-overlay">
<div class="overlay-links" style=" float:left;"> <div class="absolute-center ">Details</div></div>
<a href=""> <div class="overlay-links" style=" float:right; border-right:none;"> <div class="absolute-center comparison">Add to compare</div>
</div></a>
</div>
Javascript
/show overlay when one checkbox is checked and add its name/image to the empty space
$('.comparison').click(function(e){
var clgId = $(this).parentsUntil('.individual-clg-container').find('.image-header').text();
e.preventDefault();
var clg = $("<li></li>")
clg.text(clgId);
var removeLink = $("<a href=''>(Remove)</a>");
clg.append(removeLink)
$('.comparison-colleges').append(clg);
$('.add-to-compare-overlay').show("slide", { direction: "up" }, 300);
});
I want the text in the div containing class 'image-header' to be assigned to the variable clgId. The problem that i am facing with my code is that it is adding the text of all the divs containing class 'image-header'. Ex i want the value text1 to be assigned on clicking add to compare of the div with id text1. However it assigns 'text1 text2 text3' to clgId.
Please help
I've created a JSFiddle with what I think is your desired functionality (I included a console log output in the script of the clgId variable):
http://jsfiddle.net/py38kuvv/
I replaced the parentsUntil function with the closest function (and replaced the individual-clg-container class selector):
var clgId = $(e.target).closest('.individual-college-container').find('.image-header').text();
and also updated your click handler:
$('.comparison').on( "click", function(e) {
In order to get a quicker response in future, posting a JSFiddle of what you have so far makes it easier for others to help :)
It is adding all of them because
var clgId = $(this).parentsUntil('.individual-clg-container').find('.image-header').text();
should be
var clgId = $(this).parentsUntil('.individual-college-container').find('.image-header').text();

jquery: how to append DOM element to selector within variable containing other DOM elements

When storing DOM elements in a javascript variable prior to appending them to the actual DOM is there a way with jQuery to select elements inside the variable?
For example,
I have a list of tweets on my page. Every time I click a refresh button I append a new tweet to the list below.
I add the new tweet like follows:
new tweet
<li class="tweet normal-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name"></div>
</div>
<div class="text">Once in a lullaby</div>
<div class="time-stamp" data-time="1322631934000">1322631934000</div>
</div>
</li>
Inside each tweet on the page, not the new tweet yet, I use jQuery to append some elements.
I have:
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
and I append it to the element with the .content class
$(actionsMarkup).appendTo('#tweets .tweet .content');
Now, when I make a new tweet I do the following:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
actionsMark = $(actionsMarkup);
$(newTweet.appendTo('#tweets');
I need to be able to append the actionsMark contents to the div with class .content. However, I can't just reapply my prior statement of
$(actionsMarkup).appendTo('#tweets .tweet .content');
because that puts the markup on all .content divs again, even if it is already there.
Is there a way for me to use selectors to access the DOM nodes in my newTweet variable before I append it to the document object?
I am thinking something like
$(actionsMarkup).appendTo( newTweet, '.content');
If there is no way with selectors to do this then what are some other quick ways?
List of Tweets and Tweet container
<ul id="tweets" class="normal-tweet show-promoted-tweets">
<li class="tweet promoted-tweet" data-user-name="Dorothy">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=Dorothy" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/Dorothy" title="Dorothy">Dorothy</a>
<div class="full-name">Dorothy</div>
</div>
<div class="text">Somewhere over the rainbow</div>
<div class="time-stamp" data-time="1322631934000">3 minutes ago</div>
</div>
</li>
<li class="tweet promoted-tweet" data-user-name="lion">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=lion" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/lion" title="lion">lion</a>
<div class="full-name">Lion</div>
</div>
<div class="text">Way up high,</div>
<div class="time-stamp" data-time="1322631934000">17 minutes ago</div>
</div>
</li>
<li class="tweet normal-tweet" data-user-name="scarecrow">
<div class="image">
<img height="48" width="48" src="http://twitter.com/api/users/profile_image?screen_name=scarecrow" alt="" />
</div>
<div class="content">
<div class="user">
<a class="user-name" href="http://twitter.com/scarecrow" title="scarecrow">scarecrow</a>
<div class="full-name">Scarecrow</div>
</div>
<div class="text">And the dreams that you dreamed of,</div>
<div class="time-stamp" data-time="1322631934000">32 minutes ago</div>
</div>
</li>
</ul>
You can use .last(), to select the last element after you append your new tweet, like below:
$(document).on('click', '.refresh', function() {
newTweet = $(<new tweet code from above>);
$(newTweet).appendTo('#tweets');
var actionsMarkup =
"<div class='actions'>
<span class='favorite'>Favorite</span>
<span class='retweet'>Retweet</span>
<span class='reply'>Reply</span>
</div>";
$("#tweets .tweet").last().find(".content").append(actionsMarkup);
});
if you insist to use appendTo(), you can try using :last-child:
$(actionsMarkup).appendTo('#tweets .tweet:last-child .content');
I was looking to see if you can do the same thing, found this question but the existing answer is not useful in my case as i would like to alter the element before adding.
You can create a new dom element in a variable with jQuery and do operations on it as if it is already in the dom before appending it.
Example:
var newTweet = $('<div></div>');
newTweet.addClass('tweet');
newTweet.append('<span class="username"></span>');
newTweet.find('span.username').html('John Doe');
$('body').append(newTweet);
the following will be appended to the body:
<div class="tweet"><span class="username">John Doe</span></div>
Very handy if you are building a reusable interface element (like a dialogue box) with multiple options.

JQuery Parent-Child Selection

I am new to jQuery and am trying to write a script that will run through a menu list and display the correct background image based on the menu item. The menu list is going to be randomly populated so a script is necessary to load the correct image.
The problem is that the attribute where I am able to see which item the menu belongs to is not on the list item itself but on a div contained inside the list item. My question is is it possible to select a child element of the already selected element ?
E.g (the menuli a segment)
$(document).ready( function() {
$(menuli).each( function(index) {
$itemnumber = $(menuli a).attr("href");
switch($itemnumber) {
case 1:
$(this).css("background-image", "image01.jpg");
break;
}
});
});
This is more or less the script I am trying to get, where each list item is iterated through and depending on the href of the link inside the list item a background image is set to that list item.
EDIT
Here is my html:
<div id="divMenuSportGSXSports">
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=468&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl00_lnkSport" href="/Sport/Groups.aspx?IDSport=468&Antepost=0">
<span title="SOCCER">SOCCER</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=520&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl01_lnkSport" href="/Sport/Groups.aspx?IDSport=520&Antepost=0">
<span title="BASEBALL">BASEBALL</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=544&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl02_lnkSport" href="/Sport/Groups.aspx?IDSport=544&Antepost=0">
<span title="CRICKET">CRICKET</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=525&Antepost=0&Tema=Supabets)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl03_lnkSport" href="/Sport/Groups.aspx?IDSport=525&Antepost=0">
<span title="BASKETBALL">BASKETBALL</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=534&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl04_lnkSport" href="/Sport/Groups.aspx?IDSport=534&Antepost=0">
<span title="ICE HOCKEY">ICE HOCKEY</span>
</a>
</div>
</div>
<div class="VociMenuSportG">
<div class="ImgSport" style="background-image:url(../ImgSport.ashx?IDBook=53&IDSport=523&Antepost=0&)">
<img src="buttons_void.png">
</div>
<div class="NomeSport">
<a id="h_w_PC_cSport_repSport_ctl05_lnkSport" href="/Sport/Groups.aspx?IDSport=523&Antepost=0">
<span title="TENNIS">TENNIS</span>
</a>
</div>
</div>
</div>
Yes you can, use find
var parentElement = $('#someElement');
var childElement = parentElement.find('.child'); //where .child should be your child selector
Where as example code is not clear, I just gave answer to your question.
try to change this:
$(this).css("background-image", "image01.jpg");
to this:
$(this).children("div").css("background-image", "image01.jpg");
If you want to target the direct child of the element, better to use children() than find()
Please refer to this: What is fastest children() or find() in jQuery?

Categories

Resources