So let's say I have this scenario of articles:
I have a photo in the left and the content of the article right after the image.
In the content area I have a reservation button.
If the article is reserved, then it will be displayed a small image over the bottom of the photo (transparent written "Reserved").
This stuff is all done.
What I want to do next is to remove the hyperlink-button "Reserve" from the article if it's reserved. Should look like this:
-NormalIMG- [Reservation-Button]
-NormalIMG- [Reservation-Button]
-ReservedIMG- *
-NormalIMG- [Reservation-Button]
-ReservedIMG- *
-NormalIMG- [Reservation-Button]
and so on.
*here's no reservation button
So it's something like this:
Reserve
<!-- reserved article -->
<div class="article">
<div class="image"></div>
<div class="image-reserved"><img src="reserved.jpg" /></div>
<div class="content">
Reserve
</div>
</div>
<!-- reserved article //-->
<!-- unreserved article -->
<div class="article">
<div class="image"></div>
<div class="image-reserved"></div>
<div class="content">
Reserve
</div>
</div>
<!-- unreserved article //-->
<!-- reserved article -->
<div class="article">
<div class="image"></div>
<div class="image-reserved"><img src="reserved.jpg" /></div>
<div class="content">
Reserve
</div>
</div>
<!-- reserved article //-->
I tried with jQuery something like this:
if(!($('.image-reserved').find(img))) {
$('.reserveLink').addCSS('display', 'none');
}
But I got all the "Reserve" links removed...
I realized that I need something that should apply that CSS attribute only after the element 'img' was found.
After that, it should continue the search and apply it when it has to.
I lost all my day trying to figure out a way to get out of this by implementing different structures (using find, has, next, etc.) similar to the above example... but no success.
I'm posting here as a last resort, my hope is completely lost to something that seemed to be so easy to implement...
IMPORTANT NOTE: I know the structure looks weird and it might be really hard for what I want to be implemented, but I am not allowed to modify any code that was written already.
You shoud iterate over each image-reserved :
// For each image reserved
$(".image-reserved").each(function(){
// Count the children
var count = $(this).children("img").length;
// If there's a child (The reserved img), then we delete the following links
if(count > 0){
$(this).next().children(".reserveLink").hide();
}
});
$('.image-reserved').next().hide()
I'd suggest:
$('.content').filter(function(){
return $(this).prev('div.image-reserved').find('img').length;
}).find('a').remove();
JS Fiddle demo.
References:
filter().
find().
prev().
remove().
$('div.image-reserved:not(:empty)+.content a.reserveLink') will find all .image-reserved divs that have content, and select the .reserveLink links in the .content element after them.
Related
Here's the challenge:
We have an image and text that describes it all nested in the same div. When somebody clicks on that image, we want Google Tag Manager to return that text.
Basically, we need to:
Go up 3 parent nodes
Go down to the child node with the class "right-section"
Go down to the child node with the class "is-title"
Go down to the child node with the tag "a"
Extract the text
Using my crude, self-taught Javascript knowledge, I came up with this monstrosity of a function:
function(){
return el.parentNode.parentNode.parentNode.getElementsByClassName("right-section")[0].getElementsByClassName("is-title")[0].getElementsByTagName("a")[0].innerText;
}
... which does not work at all.
Any suggestions?
this is an example markup basically the idea is use closest function to go up to dom tree and then use 'querySelector' with that result to go down to any element inside it
const img = document.querySelector(".item_image")
img.onclick = e=>{
const root = e.target.closest(".card") // goind back to root element
const text = root.querySelector(".text") // going down to text element
console.log(text.innerText)
}
<div class="card" style="width:400px;">
<div class="sections">
<img class="item_image" style="width:200px;" src="https://2.img-dpreview.com/files/p/E~C1000x0S4000x4000T1200x1200~articles/3925134721/0266554465.jpeg" alt="">
</div>
<div class="another-seci">
<div class="text">
Despite its modest MSRP, Fujifilm's entry-level X-A3 has dual control dials, a tilting touchscreen, and the same 24MP sensor from the company's flagship models - but with a traditional Bayer color filter array instead of X-Trans. We're pushing through our full
</div>
</div>
</div>
ok, Here is an example of what you need to do. If you need an exact answer that would work by just copy pasting it, show the block of HTML exactly how Amir did. I used Amir's HTML example to do the trick. Also, if you see that it takes the same text when you click on different images, include in your html snippet the code from other images, so that we could see how they relate to the parents and could refine the selectors.
Here's your CJS code:
function(){
return {{Click Element}}.parentElement.parentElement.querySelector(".text").innerText
}
There's completely no need to hop from node to node once you got to the bottom. From the bottom parentElement, just do the query selector once and you're in good hands.
You could also use .closest, but it seems like its complexity is way over just a few parentElements. I know it's insignificant, but hey.
Here is how I debug it right on this page (in Amir's answer):
document.querySelectorAll('.item_image').forEach(item => {
item.addEventListener('click', event => {
const root = event.target.closest(".card") // goind back to root element
const text = root.querySelector(".text") // going down to text element
console.log(text.innerText)
})
})
<div class="card" style="width:400px;">
<div class="sections">
<img class="item_image" style="width:200px;" src="https://2.img-dpreview.com/files/p/E~C1000x0S4000x4000T1200x1200~articles/3925134721/0266554465.jpeg" alt="">
</div>
<div class="another-seci">
<div class="text">
Despite its modest MSRP, Fujifilm's entry-level X-A3 has dual control dials, a tilting touchscreen, and the same 24MP sensor from the company's flagship models - but with a traditional Bayer color filter array instead of X-Trans. We're pushing through our full
</div>
</div>
</div>
<div class="card" style="width:400px;">
<div class="sections">
<img class="item_image" style="width:200px;" src="https://2.img-dpreview.com/files/p/E~C1000x0S4000x4000T1200x1200~articles/3925134721/0266554465.jpeg" alt="">
</div>
<div class="another-section">
<div class="text">
BlaDespite its modest MSRP, Fujifilm's entry-level X-A3 has dual control dials, a tilting touchscreen, and the same 24MP sensor from the company's flagship models - but with a traditional Bayer color filter array instead of X-Trans. We're pushing through our full
</div>
</div>
</div>
Here's what ultimately worked, for anyone Googling this:
function (){
el = {{Click Element}};
var item = el.parentElement.parentElement.nextElementSibling.getElementsByTagName('a')[0].innerText;
return item;
}
I'm brand new to javascript/jquery, but have been going okay so far (though you'd hate to see my code), but I've hit a wall with trying to strip out style tags from some HTML I'm trying to clone.
The reason for cloning is that the CMS I'm forced to use (which I don't have access to code behind, only able to add code over the top) automatically builds a top nav, and I want to add a duplicate sticky nav once the user scrolls, but also add a couple of elements to the scrolled version.
The original HTML of the top nav looks a bit like like:
<nav id="mainNavigation" style="white-space: normal; display: block;">
<div class="index">
Participate
</div>
<div class="index" style="margin-right: 80px;">
News
</div>
<div class="index active" style="margin-left: 80px;">
<a class="active" href="/about/">About</a>
</div>
<div class="external">
Collection
</div>
<div class="index">
Contact
</div>
</nav>
I had mild success (other than those style tags I want to remove) with the following, even though it doesn't seem to make sense to me, as I expected some of the elements would be repeated (the whole < nav >…< /nav > tag should have been within the #mainNavigation clone, no?):
var originalNavItems = $('#mainNavigation').clone().html();
$("#site").prepend('
<div id="ScrollNavWrapper">
<div class="nav-wrapper show-on-scroll" id="mainNavWrapper">
<nav id="newScrolledNav" style="white-space: normal; display: block;">
<div class="index home">
Home
</div>
' + originalNavItems + '
<div class="newItem">
<a href="http://www.externalsite.com">
View on External Site
</a>
</div>
</nav>
</div>
</div>');
I've tried to use a few answers from related questions on here, but I keep getting incorrect results. Can you help me?
You can strip the style elements like so:
var el = $('#mainNavigation'); // or whatever
el.find('[style]').removeAttr('style');
You can use
var originalNavItems = $('#mainNavigation').clone().find("*").removeAttr("style");
Then you can use .append() to add that html elements
Fiddle
You can clone into an imaginary div and then fetch the mainNavigation also. You can also remove the style attributes along with that. Hope this works for you...
var temp = $('<div />').html($('#mainNavigation').clone());
temp.find('*').removeAttr('style');
originalNavItems = temp.html();
The nav is cloned but the html() function only returns the HTML for the contents and that's why it disappears. You can avoid some string manipulation by adding the cloned element directly before a target element.
$("#site").prepend('
<div id="ScrollNavWrapper">
<div class="nav-wrapper show-on-scroll" id="mainNavWrapper">
<nav id="newScrolledNav" style="white-space: normal; display: block;">
<div class="index home">
Home
</div>
<div class="newItem">
<a href="http://www.externalsite.com">
View on External Site
</a>
</div>
</nav>
</div>
</div>');
$('#mainNavigation').clone()
.find('[style]').removeAttr('style').end()
.insertBefore('#newScrolledNav .newItem');
In the previous case find('[style]') matches elements that have a style attribute.
I'm new to Stack Overflow (and js in general), so this might be really bad ettiquette, but I seem to have accidentally fixed it myself trying to debug my implementation of the first upvoted answer that #Anoop Joshi gave above. Please comment and let me know if it would have been better to just edit my question!
I decided to break the process down into separate steps – similar to #Kiran Reddy's response actually, but I hadn't got to trying his yet.
I tried:
var styledHTML = $('#mainNavigation').clone();
styledHTML.find("div[style]").removeAttr('style');
var originalNavItems = styledHTML.html();
$("#site").prepend('<div… etc.
with a console.log(styledHTML) etc under each line to check what I had at each stage – and it worked! (The code did, console.log didn't?)
I was just doing this to try and log the value of the variables at each stage, but whatever I did fixed it…
Now I need to figure out why I can't even make console.log(variable); work :-/
Try this code
$('#mainNavigation').children().removeAttr('style');
Hope this will help you.
I have some text in a website that I want to change using javascript because I can't change it any other way.
In short, the site is laid out like such:
...some other divs before here, body, head, etc...
<div id="header" class="container-fluid clearfix">
<div class = "hero-unit">
<h1 class="title">Support Center</h1>
...some other divs for other parts of the page...
</div>
</div>
...more divs, footer, etc...
I don't need the text to change on click or anything like that I just want it to be set on load to something different than Support Center but I'm not sure if I'm placing the script in the correct place or if the syntax is wrong?
I've tried placing it before and after and it doesn't seem to work. Here is the code:
<script type="text/javascript">
var targetDiv = document.getElementByID("header").getElementsByClassName("hero-unit")[0].getElementsByClassName("title")[0];
targetDiv.innerHTML = "Please use the Knowledge Base to find answers to the most frequently asked questions or you may submit a support ticket which will be sent to your COM email account.";
</script>
Thank you.
Looking at the actual source of your page, your page does not contain a h1 element with a class of title.
Your actual source code
<div id="header" class="container-fluid clearfix">
<div class="hero-unit"></div>
<div class="container-fluid clearfix">
<div class="row-fluid">
<div class="leftcolumn"></div>
<div class="rightcolumn"></div>
</div>
</div>
</div>
This means it does not exist till some point after your page loads. You need to put your code after the code that generates the h1 title element
In jQuery (if you can use it), you'd use something like
$("#title").text("Something else");
it looks like you are not getting the specific class to change the html
try with querySelector like i have done
JS Fiddle
var targetDiv = document.querySelector('#header > .hero-unit > h1.title')
targetDiv.innerHTML = "Please use the Knowledge Base to find answers to the most frequently asked questions or you may submit a support ticket which will be sent to your COM email account.";
my goal is to show an overlay on a div when that div is hovered on. The normal div is called .circleBase.type1 and the overlay is circleBase.overlay. I have multiple of these divs on my page. When I hover over one .cirlceBase.type1, overlays show on every .circleBase.type1. How do I prevent this?
Here is some code:
HTML
<div class="circleBase type1">
<p class="hidetext">Lorem ipsum</p>
<hr size="10">
<strong class="gray hidetext">gdroel</strong>
</div>
<div class="circleBase overlay">
<p class="date">11/12/14</p>
</div>
and jQuery
$(document).ready(function(){
$('.overlay').hide();
$('.date').hide();
$(".circleBase.type1").mouseenter(function(){
$(".overlay").fadeIn("fast");
$('.date').show();
$('.hidetext').hide();
});
$(".overlay").mouseleave(function(){
$(this).fadeOut("fast");
$('.date').hide();
$('.hidetext').show();
});
});
Use $(this) to get current element reference and do like this:
$(".circleBase.type1").mouseenter(function(){
$(this).next(".overlay").fadeIn("fast");
$(this).next(".overlay").find('.date').show();
$(this).find('.hidetext').hide();
});
and:
$(".overlay").mouseleave(function(){
$(this).fadeOut("fast");
$(this).find('.date').hide();
$(this).prev(".circleBase").find('.hidetext').show();
});
usually when I want to target something specific you just give it an ID.
ID's play better in JavaScript than classes.
If you had a specific container, using the container as your starting point is a good route as well
$('#container').find('.something.type1').doSomething();
This is much more efficient for jquery, because it only searches .something.type1 inside of #container.
Well I'm not sure exactly what you're looking to do, but it looks like you want to replace content in some kind of circle with a hover text, but with a fade. To do that you'll have to add some CSS and it would be best to change your HTML structure too.
The HTML should look like this:
<div class="circleContainer">
<div class="circleBase">
<p>Lorem ipsum</p>
<hr>
<strong class="gray">gdroel</strong>
</div>
<div class="overlay" style="display: none;">
<p class="date">11/12/14</p>
</div>
</div>
so your js can look like this:
$(function(){
$(".circleContainer").mouseenter(function(){
$(this).find(".overlay")
$(this).find('.circleBase').hide();
});
$(".circleContainer").mouseleave(function(){
$(this).find('.circleBase').show();
$(this).find(".overlay").hide();
});
});
Here's a working solution that includes some CSS to make it nice. Try taking it out and running it, you'll see the problems right away.
I have a two-column page (<p> tags after the first half are moved to column 2 with javascript).
My problem is that I want to break it up into "pages" like you'd see if you were reading a PDF.
Is there a neat way to do this? Or do I need to check if each page is overflowing programmatically as I fill them? Would that even work?
A possible way to do it is to make all different div's with all the copy in it and then with scrollTop go to the according page/collumn.
Something like:
<div id="page1" class="page">
<div id="p1_column_1" class="column">Here all the copy</div>
<div id="p1_column_2" class="column">Here all the copy</div>
</div>
<div id="page2" class="page">
<div id="p2_column_1" class="column">Here all the copy</div>
<div id="p2_column_2" class="column">Here all the copy</div>
</div>
Then css give it a height a width and overflow hidden and then with javascript/jquery something like:
var curr_col = 0;
var col_height = $('.column').height();
$('.column').each(function() {
$(this).scrollTop(col_height*curr_col);
curr_col++;
})
Edit
Check this fiddle to see the result: http://jsfiddle.net/taPjR/3/ .
In the example I copied the text with jQuery from the first div.
And I know it's very a dirty way, but I'm not sure if there is another keeping different fonts/font sizes and the images in the copy in mind.
Maybe a pdf generator like LaTex (http://www.latex-project.org/) could also be interesting?
Hope I could help.