Hey there StackOverflow Community!
I'm fairly new to Stack and coding in general so this code will probably have an obvious error that I can't figure out.
Basically, in the following code I want everything shown on screen that isn't the element with the id settings to be hidden.
if ((!"#settings").style.display === "block") {
$(!"#settings").hide();
}
HTML:
<body>
<span id="mainBtnArea">
<button id="settings-btn">Settings</button>
<button id="stats-btn">Stats</button>
</span>
<div id="mainArea">
<h1 id="clickHeader"></h1>
<button id="main-btn">Click Me</button>
</div>
<div id="settings">
<h1>this is the page I want to show</h1>
</div>
<div id="stats">
<p id="stats-clicks" class="stats">Keys:</p>
<p id="stats-keys" class="stats">Keys:</p>
</div>
</body>
Query selectors don't work quite like that - you can't negate a selector with a ! symbol.
You can, however, use the visible selector and the not selector. The following will hide every element that is a child of body ($("body.find"), is a div or span (div, span), is visible (:visible), and doesn't have the id 'settings' (:not('#settings'))
$("body").find("div:not('#settings'), span").hide()
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
if (elements[i].id != 'settings') {
elements[i].style.display = 'none';
}
}
You need to have a forloop!
Update: You have to add an element tag DIV in order for it to work. Please see above.
It works for me:
https://jsfiddle.net/bowtiekreative/j697okqd/1/
Related
I have this HTML code (and the number of components that I want to edit it's variable, it could be 3 or 20).
I have created a small example with similar scenario on my website
As you can see my script is able to edit the father div and add the classname. Same for firstchild.
I would like to edit all divs inside firstchild but not the immediately div, it has to be two inside.
Any ideas why my code is not working on the last part?
Thanks.
// WORKS OK
var firstc = document.getElementById('father');
firstc.classList.add("father-class");
firstc.children[0].children[0].children[0].setAttribute("id", "firstchild"); // WORKS OK
var second = document.getElementById('firstchild');
second.classList.add("child-class");
// NOT WORKING
var grandchildren = second.children[0].children[0].children[0];
for (let z = 0; z < grandchildren.length; z++) {
grandchildren[z].classList.add("slide");
}
<div id="father">
<div>
<div>
<div id="firstchild">
<div>
<div>
<div class="random63637236">
<li>1</li>
</div>
<div class="generic">
<li>2</li>
</div>
<div class="italy_gdgd">
<li>3</li>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
the problem in your code is the last children[0]. you are selecting only the first div, it's not an array. Fix that line and everything will work
var grandchildren = second.children[0].children[0].children;
As a side note: if for some reason the first or the second .children[0] are undefined you will get an error.
A better approach is to use querySelectorAll which returns an array;
if your array it is empty, nothing happens.
second.querySelectorAll('#firstchild > div > div > div')
.forEach(el => el.classList.add('slide'))
I'd like to have basic code like the following:
<span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span>
However, I'd like to keep it from firing both of these events if both are being hovered over; e.g. if I hover over "this" it should fire only its event and alert "hello." How can I do this?
Thank you in advance!
$(".container").hover(function(){
alert($(this).attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="container" id="hi">
Hello,
</span>
<span class="container" id="hello">
this
</span>
<span class="container" id="hi">
is a test
</span>
I am going to assume that the overlapping elements are not the same size. I.e one is bigger than the other.
HTML and inline js:
<span class="container" id="hi">
Hello,
</span>
<span class="container " id="hello">
this </span>
<script>
var hello =
document.getElementById("hello");
var this =
document.getElementById
("this");
hello.addEventListener("click
",pop("hello"));
this.addEventListener("click",pop(" hi");
function pop(string) {
window.alert(string);
}
<\script>
That being said very little is mentioned about the nature of the elements this and hello. Op plz show your CSS and update ques
Here's the relevant portion of what I ended up using. I used JQuery.
var mouseHovered = function(element) {
//get all hovered spans
var hoveredElements = $("span:hover");
//get the element with the smallest text
var smallestElement;
for(var i=0; i<hoveredElements.length; i++) if(!smallestElement || hoveredElements[i].textContent.length < smallestElement.textContent.length) smallestElement = hoveredElements[i];
//if this is the smallest text in the elements
if(element == smallestElement) {
//log the text
console.log(element.textContent);
}
}
You need to prevent Event bubbling when you hover/click on inner span.
This can be done using event.stopPropagation().
Look at two solutions provided at this JSFiddle.
Solution 1 - Use of e.stopPropagation() in the handler function innerSpan().
Solution 2 - Use of event.stopPropagation() in inline onclick event.
<span onclick="alert('Outer span');">
Outer
<span onclick="event.stopPropagation(); alert('Inner span');">
Inner
</span>
</span>
I'm trying to make a script which will change the content of every occurence like this:
<div id="random numbers">
<div class="column-1"></div>
<div class="column-1">this value I want to change</div>
<div class="column-1"></div>
</div>
there's many of those^
so far, this is the code I'm trying to make use of:
var elements = document.querySelectorAll('column-1');
for ( var i=elements.length; i--; ) {
elements[ i ].InnerHTML = "test";
}
but this isn't working, and I'm really just trying to piece together some code that will replace the content of the #2 column-1 of every <div id="random numbers">
I appreciate any help here, thanks in advance
There are two problems with your above code. First, your .querySelectorAll() should be targeting the class; you need to specify the full stop. Second, the i in .innerHTML needs to be lowercase.
After these two bugs have been fixed, you can only apply the change to every second element by running a condition based on a modulo of 2 using i % 2 as follows:
var elements = document.querySelectorAll('.column-1');
for (var i = 0; i < elements.length; i++) {
if (i % 2) {
elements[i].innerHTML = "OVERRIDDEN";
}
}
<div id="random numbers">
<div class="column-1">Should STAY</div>
<div class="column-1">Should CHANGE</div>
<div class="column-1">Should STAY</div>
</div>
If you're specifically trying to target the <a> tags, you can do that directly with querySelectorAll('.column-1 a') itself, using .outerHTML if you want to replace the <a> tag itself. Note that this doesn't require a conditional:
var elements = document.querySelectorAll('.column-1 a');
for (var i = 0; i < elements.length; i++) {
elements[i].outerHTML = "OVERRIDDEN";
}
<div id="random numbers">
<div class="column-1">Should STAY</div>
<div class="column-1">Should CHANGE</div>
<div class="column-1">Should STAY</div>
</div>
Hope this helps! :)
I'm using a script that checks for any tag that also has a SRC="self". My function should function like this:
Check if img src="self"
If true, hide the parent div
If false, do nothing
Currently the function actually hides every img regardless of src. If I replace the jQuery hide() action then the function works perfectly. It just seems like it isn't quite performing the hide function like I anticipated.
function changeSourceAll() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
if (images[i].src.indexOf('self') !== -1) {
$(".redditThumbnail").hide();
}
else (){}
}
}
changeSourceAll();
Sample HTML is below. I have multiple .listrow div elements identical to this and the function removes all the .redditThumbnail divs.
<div class="listrow news">
<div class="newscontainer">
<div class="redditThumbnail"></div>
<div class="articleheader news">
<div class="actionmenu">
<p class="mediumtext floatleft alignleft">
author
</p>
<div id="redditUsername"></div>
<div class="floatright">
<div class="redditPermalink material-icons"></div>
</div>
</div>
<p class="redditTitle mediatitle news"></p>
</div>
</div>
</div>
Thanks!
You could use an attribute-equals selector to find all of the <img> elements that point to "self" and then hide their parents :
// Hide the closest thumbnail for elements that match this constraint
$('img[src="self"]').closest('.redditThumbnail');
Example
$(function() {
$('button').click(function(){
$('img[src="self"]').closest('.redditThumbnail').hide();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='redditThumbnail'>
A (has self)
<img src='self' />
</div>
<div class='redditThumbnail'>
B (doesn't have self)
<img src='self-test' />
</div>
<div class='redditThumbnail'>
C (has self)
<img src='self' />
</div>
<hr />
<button>Hide Self-Referencing Images</button>
The issue with hiding every img is because you select and hide all .redditThumbnail elements for every matching item. To fix this you could use this:
$(images[i]).closest('.redditThumbnail').hide();
However a better approach entirely would be to use filter() and find only the .redditThumbnail elements which match the requirements. Try this:
$('.redditThumbnail').filter(function() {
return $(this).find('img[src="self"]').length != 0;
}).hide();
You are hiding all: $(".redditThumbnail").hide();. I guess you should do something like $(images[i]).hide();
I have this code in my HTML:
<!DOCTYPE html>
<head></head>
</body>
<div class="exercise ex1">
<h1>Zadanie 1</h1>
<div>
<h3>Chrome</h3>
<div class="chrome"></div>
Opera
</div>
<div>
<h3>Microsoft Edge</h3>
<div class="edge"></div>
Microsoft Edge
</div>
<div>
<h3>Firefox</h3>
<div class="firefox"></div>
Opera
</div>
</div>
</body>
</html>
and I have no idea, how to get to my a tags, so I could change their inner HTML and hrefs in JavaScript. I'll be very grateful for your help!
You can use document.querySelectorAll("a") and a for loop to iterate all a elements in document.
Note, appear to be missing <html> tag , first body element tag should be <body> , not closing </body> tag
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="exercise ex1">
<h1>Zadanie 1</h1>
<div>
<h3>Chrome</h3>
<div class="chrome"></div>
Opera
</div>
<div>
<h3>Microsoft Edge</h3>
<div class="edge"></div>
Microsoft Edge
</div>
<div>
<h3>Firefox</h3>
<div class="firefox"></div>
Opera
</div>
</div>
<script>
var a = document.querySelectorAll("a");
for (var i = 0; i < a.length; i++) {
console.log(a[i], a[i].innerHTML, a[i].href)
}
</script>
</body>
</html>
You can use querySelectorAll and iterate over the elements
var anchors = document.querySelectorAll('a');
for ( var i = anchors.length; i--; ) {
anchors[i].innerHTML = 'something else';
anchors[i].href = 'http://someother_url.com';
}
Like this:
document.getElementsByTagName("A")
which returns a collection of elements - more specifically, a NodeList object. This can then be accessed in a similar manner to an array:
var allAs = document.getElementsByTagName("A");
console.log(allAs[0].href); //will print "https://www.google.pl/chrome/browser/desktop/index.html"
If you want to know more about how to use this, read more at https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
As millerbr pointed out, document.getElementsByTagName("A") will return an array like object. You can then edit the hrefs innerHTML by going document.getElementsByTagName("A")[0].innerHTML = "NotChrome"
Check out this jsFiddle
You can iterate over the links in a document using the document.links collection, which contains all A and MAP elements with an href attribute, e.g.
Array.prototype.forEach.call(document.links, function(link) {
console.log(link.href);
});
Note that A elements without an href aren't links, they're anchors (i.e. they are the target of a link). Using getElementsByTagName('a') will return all A elements, including those that aren't links.