document.querySelector() does not working - javascript

Is there any dependency problem?
because I am using the only pure javascript there is no jquery or anything.
Using node.js
Here is my code
window.onload()=function(){
var left=document.querySelector('.left');
var right=document.querySelector(".right");
var container=document.querySelector(".container");
console.log(left);
left.addEventListener('mouseenter',()=>{
container.classList.add('hover-left');
})
left.addEventListener('mouseleave', () => {
container.classList.remove('hover-left');
})
right.addEventListener('mouseenter', () => {
container.classList.add('hover-right');
})
right.addEventListener('mouseleave', () => {
container.classList.remove('hover-right');
})
}
<div class="container">
<div class="split left">
<h1>The Designer</h1>
Read more
</div>
<div class="split right">
<h1>The Programmer</h1>
Read more
</div>
</div>

I got this error on Chrome:
Uncaught TypeError: window.onload is not a function
Removing the parentheses the error was gone.
But i didn't get how your page should work.
Look for more information here:
https://stackoverflow.com/questions/29927638/window-onload-work-but-chrome-console-says-uncaught-typeerror-window-onload-is

If you select your DOM Elements with the CSS-Selector '.' for classes you get a list of elements instead of a single element which you can directly manipulate.
If left, right and container only appear once on your page, it's best to use ids:
JS:
window.onload=function(){
var left=document.getElementById('left');
var right=document.getElementById("right");
var container=document.getElementById("container");
console.log(left);
left.addEventListener('mouseenter',()=>{
container.classList.add('hover-left');
})
left.addEventListener('mouseleave', () => {
container.classList.remove('hover-left');
})
right.addEventListener('mouseenter', () => {
container.classList.add('hover-right');
})
right.addEventListener('mouseleave', () => {
container.classList.remove('hover-right');
})
}
HTML:
<div id="container" class="container">
<div class="split" id="left">
<h1>The Designer</h1>
Read more
</div>
<div class="split" id="right">
<h1>The Programmer</h1>
Read more
</div>
</div>
Also as a comment above points out you mustn't use brackets when setting onload event.

If you have any static JS files being loaded in the tag in your html requesting to please load the JS at the end of the html body. Document wont be ready until the JS is loaded hence the document will be null.

Related

Javascript loop to eliminate elements that do not start with certain value

I have links embedded inside .media-body .media-heading in the HTML example. I'm wanting to write JS to remove any link where the text does not start with the value attribute in the input element, in this case "A"
I've done a manual version below that checks the first A tag and manually removes the other A tag on the click of a button if the text doesn't start with "A". I need this to somehow loop through and do this automatically on page load but not sure how I do that. Any help is appreciated.
<!DOCTYPE html>
<html>
<body>
<input type="text" name="search" value="A" class="searchbox">
<div class="media-body">
<div class="media-heading">
A doc beginning with A
</div>
</div>
<div class="media-body">
<div class="media-heading">
Doc beginning with D
</div>
</div>
<button onclick="startFunction()">Remove wrong doc</button>
<script>
function startFunction() {
var az = document.getElementsByTagName("input")[0].getAttribute("value");
var getstart = document.getElementsByTagName("a")[0].innerHTML;
var searchletter = getstart.startsWith(az);
var myobj = document.getElementsByTagName("a")[1];
if(searchletter = az)
{
myobj.remove();
}
}
</script>
</body>
</html>
The second part of your question as how to do this automatically on page load is answered rather quickly. Conveniently you already wrapped the functionality inside it's own function - startFunction(). So all you have to do is execute that function after the <body> definition of your html code.
The first part isn't much more difficult as you also almost have anything you need set up yet. The only thing that's missing is looping over the HTMLCollection - more or less an array - retrieved by executing document.getElementsByTagName("a") using a simple for-loop.
There's a catch though: as you loop over the HTMLCollection and eventually remove an object from the DOM using .remove() you're ultimately changing the collection too. In other words, if you remove an object, the list shrinks by one element. To compensate your loop needs to start with the initial number of elements and decrement by one.
Here's an example:
function startFunction() {
let az = document.getElementsByTagName("input")[0].getAttribute("value");
let elements = document.getElementsByTagName("a");
let element;
for (let a = elements.length - 1; a >= 0; a--) {
element = elements[a];
if (!element.innerHTML.startsWith(az)) {
element.remove();
}
}
}
startFunction();
<input type="text" name="search" value="A" class="searchbox">
<div class="media-body">
<div class="media-heading">
A doc beginning with A
</div>
</div>
<div class="media-body">
<div class="media-heading">
Doc beginning with D
</div>
<div class="media-body">
<div class="media-heading">
Something completely different
</div>
</div>

function not being called, do I need a window.load?

I am trying to change the css stylings of an item when it's clicked.
ryan.js
function ryanClicked(id){
document.getElementById(id).style.color = "blue";
alert("Asdsa");
}
product.html
<head>
<script src="ryan.js"></script>
</head>
<body>
<div id ="sizeButton1"class="sizeButton" onclick="ryanClicked(sizeButton1)"> S </div>
<div id ="sizeButton2"class="sizeButton" onclick="ryanClicked(sizeButton2)"> M </div>
<div id ="sizeButton3"class="sizeButton" onclick="ryanClicked(sizeButton3)"> L </div>
I assume I need a onReady or onLoad somewhere? I haven't done js in a while.
My page has Jquery included so I can use jquery for the ready event. I'm not sure if that would be better to do or not.
Try this, you don't need pass id to your function, instead you can pass this (refers to element that was clicked),
function ryanClicked(el) {
el.style.color = "blue";
}
<div id="sizeButton1"class="sizeButton" onclick="ryanClicked(this)">S</div>
<div id="sizeButton2"class="sizeButton" onclick="ryanClicked(this)">M</div>
<div id="sizeButton3"class="sizeButton" onclick="ryanClicked(this)">L</div>
If you are using jQuery, you might prefer:
<div id ="sizeButton1" class="sizeButton"> S </div>
<div id ="sizeButton2" class="sizeButton"> M </div>
<div id ="sizeButton3" class="sizeButton"> L </div>
and:
$(".sizeButton").on("click", function() {
$(this).css("color", "blue")
})
https://jsfiddle.net/38ybvty8/
You can get desired result without passing id and onclick attribute in your element tag.
$(".sizeButton").click(function(){
$(this).css({'color':'blue'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="sizeButton1" class="sizeButton" >S </div>
<div id ="sizeButton2" class="sizeButton" >M</div>
<div id ="sizeButton3" class="sizeButton" >L</div>

Linking a div to the href inside it

I want to make the whole staff-container linked to the first href inside of it. (The one in staff-picture). How do I write this with jQuery? I'm pretty confused with attr() and I know that I have to use it.
In the following HTML, the jQuery should make staff-container linked to google.com.
<div class="staff-container">
<div class="staff">
<div class="staff-picture">
<img src="img/people/teachers/ahmed.png" />
</div>
<p><span class="bold">Mr. Ahmed</span><br />
Ext. 13417<br />
Room 417/323<br />
email#wcskids.net</p>
</div>
</div>
EDIT: Thanks to the answers I used this jQuery:
$('.staff-container').click(function() {
window.location.href = $(this).find('a').attr('href');
});
If there is no link inside staff-picture I do NOT want it to link the email. If jQuery can't find the link in staff-picture, I want the click to do nothing.
Try like this
$('.staff-container').click(function(e) {
if($(this).find('a').attr('href'))
window.location.href = $(this).find('a').attr('href');
e.preventDafault();
});
like this..??If you want specifically first anchor tag then you can give like
window.location.href = $(this).find('a').eq(0).attr('href');
Try this:
$('.staff-container').click(function() {
var $first_link = $(this).find('a').first();
window.location.href = $first_link.attr('href');
});
Pure JS version: should be a bit faster than jQuery
<script>
function link(loc){
var href=loc.getElementsByTagName('a')[0].href;
console.log(this);
console.log(href);
loc.setAttribute("onclick","window.location.href='"+href+"'");
loc.removeAttribute("onmouseover","");
}
</script>
<div class="staff-container" onmouseover="link(this)">
<div class="staff">
<div class="staff-picture">
<img src="img/people/teachers/ahmed.png" />
</div>
<p><span class="bold">Mr. Ahmed</span><br />
Ext. 13417<br />
Room 417/323<br />
email#wcskids.net</p>
</div>
</div>
Working tested

Javascript - JQuery : Cannot find id and .html("") or getElementById and set the innerHTML

I'm new to jQuery and can't add innerhtml to a div.
I have tried getElementById and also $('').html().
My javascript
var dishes = arg;
var starterDish = dishes[0];
var mainDish = dishes[1];
var dessertDish = dishes[2];
location.href=$('#finishButton').attr('href');
//The new HTML file
alert($('#starterDishName').html());
// will only return unidentified
$('#starterDishName').html(starterDish.name);
$('#starterDishPrep').html(starterDish.description);
$('#mainDishName').html(mainDish.name);
$('#mainDishPrep').html(mainDish.description);
$('#dessertDishName').html(dessertDish.name);
$('#dessertDishPrep').html(dessertDish.description);
run4 = false;
and the finish.html file:
</div>
<div id="starterDishName" align="center"> <h3>blablabla</h3></div>
<div id="starterDishPrep" align="center"> </div>
<div id="mainDishName" align="center"> <h3></h3></div>
<div id="mainDishProp" align="center"> </div>
<div id="dessertDishName" align="center"> <h3> </h3></div>
<div id="dessertDishProp" align="center"> </div>
</div>
I think the problem is located: location.href=$('#finishButton').attr('href');
and that the new html file wont allow me to use the ID's get?
QUESTION:
How can I get the id of the new html file and change the innerhtml of it from my code's perspective?
I assume you have this in a JavaScript file as you wrote: "My .js". And if you have included it in the head-section of your HTML the script is executed immediately and the selectors are not aware of all the HTML elements. Using jQuery you can simply wrap everything into a closure as this will get executed after the DOM is parsed:
$(document).ready(function() {
// your logic goes here
});
var id = document.getElementById('id').innerHTML;

Using jQuery, how to find the index of an element amongst its siblings of a specified CSS class

Given the following HTML:
<div class="component">
<div class="component">
<div class="component">
</div>
</div>
<div class="component">
<div class="somethingelse">
</div>
<div class="component">
</div>
<div class="component">
<input type="button" value="Get Path" onclick="showPath(this)" />
</div>
</div>
</div>
I'm trying to write the function showPath so that it returns the index of the parent div in relation to its siblings of class component. So in the above sample, I would like the function to return 1.
I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse
function showPath(element) {
var component = $(element).closest('.component');
alert(component.index());
}
A quick and simple extension for jQ to turn this process into a method:
$.fn.getIndex = function(){
var index = $(this).parent().children().index( $(this) );
return index;
}
Run this on document.ready or wrap it in a function and run it that way (probably cleaner).
Usage is as simple as
var index_for_element = $('.thing-you-want-index-for').getIndex();
Try this(haven't tested):
function showPath(element) {
var component = $(element).closest('.component');
alert(component.parent().find(".component").index(component));
}
You can do this.
$('input').click(function() {
var component = $(this).closest('.component');
alert(component.parent().children(".component").index(component));
})
Check working example at http://jsfiddle.net/Qzk6A/2/

Categories

Resources