Trying to add class to parent of parent - javascript

I'm trying to add a class to a parent of a parent of a link, and have tried multiple methods without success.
Below are three attempts. It's supposed to add a class based to the parent's parent based on the href of the a so I have to reference it by url - I also don't know how many links there are for each href:
$('a[href="http://localhost/?cat=2"]').parents(":eq(1)").addClass("social-line");
$('a[href="http://localhost/?cat=3"]').parents("ul:first").addClass("knowledge-line");
$('a[href="http://localhost/?cat=4"]').closest("ul").addClass("news-line");
<ul class="post-categories">
<li>
Social
</li>
</ul>

It can be done in plain JS, without jQuery at all. Take a look at the below example:
document.querySelector('a[href="http://localhost/?cat=2"]').parentNode.parentNode.classList.add('social-line');
/* Just to demonstrate that it works */
.social-line:after {
background-color: green;
color: yellow;
content: 'It works';
}
<ul class="post-categories">
<li>
Social
</li>
</ul>
That's all I can help you with, given the amount of information you (didn't) provided.

Related

Vanilla Javascript click on LI that contains a certain text

I have some code that scans a webpage and outputs a special string, such as: multus –a –um And on the page it's executed on there are many <LI> elements containing texts like multus –a –um but, they are all different. I need a way to search the page for an element containing a certain string and then change some CSS on the <LI> element.
Example:
I run my code and get: multus –a –um
Search page for an <LI> element containing multus –a –um
Change background of element to #17af50
It need to be a function too, so I can run it easily
Take a look at the various Array methods. They are fantastic.
Array
.from(document.querySelectorAll("li"))
.filter(function(item){ return item.innerText.indexOf("foo") !== -1; })
.forEach(function(item){ item.parentNode.classList.add("highlight"); });
.highlight { background-color: #17af50; }
<ul>
<li>bar</li>
<li>foo bar</li>
</ul>
<ul>
<li>bar</li>
<li>bar</li>
</ul>

Navigation tab stay a certain color

I am using ASP.net and have a master page that utilizes navigation. My problem is when I click on a link it loads a different asp page, but the navigation tab doesn't switch to the clicked color,it reverts back to its original color. Since all the pages are loading the same, I can't just use CSS because the page is reloaded. Is there a way to write a javascript function that tells the page when it loads to display the hover color and keep it there? Since the only HTML I use is on the master page, I can't switch anything out. I'm sure there must be a way using nth-child but I can't figure it out. As for the code, a simple example is:
<div>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
So how would I get the 2nd link to switch to the hover color when loading the page?
It's been a while since I've played with asp, so I won't have the exact terms, but I can point you in the right direction.
First, in your master page, add unique ids to all of your nav links. This will make it trivial to access those links in your specific asp pages. It helps to do this because otherwise it's hard to select the link you want. jQuery such as $("div ul li:nth-child('2')") will select the second li that's a child of a ul that's a child of div, but that could happen anywhere on your page.
Once you have that, let's assume your nav panel looks like this:
<div>
<ul>
<li id="linkOne">One</li>
<li id="linkTwo">Two</li>
<li id="linkThree">Three</li>
</ul>
</div>
Then, in the page that loads when Two is clicked, you need to add a script with an onLoad handler that modifies the link:
<script>
document.onload = function() { $("#linkTwo").addClass("hover"); };
</script>
This will wait till the document loads (otherwise you may try changing an element that doesn't exist yet), then run a function that finds the specific element with the id "linkTwo" and adds the css class "hover" to it.
Obviously, this line will be different for each specific asp page - or something you can have your server-side logic calculate.
Your question is a little unclear. But if i understood right in your case i should use a specific css class that is loaded if you determine that you are on current page.
Something like this (i don't know asp, i will put a general example)
<div>
<ul>
<li <?php if($CurrentPage = 'One') {echo 'class="active"';} ?>>One</li>
<li <?php if($CurrentPage = 'Two') {echo 'class="active"';} ?> >Two</li>
<li <?php if($CurrentPage = 'Three') {echo 'class="active"';} ?>>Three</li>
</ul>
</div>
this will put a special class to your element. That class will have the hover color, and the problem is solved.
Hope you can adapt this to asp.
Use the following:
html code
<body>
<div>
<ul style="display:inline; background-color:lightgray; float:left">
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='one.html'; toggle_bgcolor(this);">One</li>
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='two.html'; toggle_bgcolor(this);">Two</li>
<li style="margin:20px; display:inline-block" onclick="frames['target'].location.href='three.html'; toggle_bgcolor(this);">Three</li>
</ul>
<iframe id="target"></iframe>
</div>
</body>
JS function
function toggle_bgcolor(elem)
{
for(var c=0; c<elem.parentNode.getElementsByTagName('li').length; c++)
{
elem.parentNode.getElementsByTagName('li')[c].style.backgroundColor='';
}
elem.style.backgroundColor='limegreen';
}
The JS-block for the onclick event in each <li> element will toggle the baclkground-color of each <li> element when another <li> is clicked.
Check this fiddle

(html/css/javascript) Trying to make my Current Page link in the navbar a different color

I've been reading around and people recommending only CSS to change the current page navbar link background color but I don't get how that's possible since CSS is static and I won't be able to add/remove the .currentlink class on the links? So right now I'm using JS / jquery to try to add / remove class based on click, but the site refreshes and nothing is saved when I click, so that the class that I added/removed doesn't do anything. May someone guide me the right direction? Example: I click on the last link of the HTML I gave you, but it would just go to that site and since everything refreshes to a new site, the background doesn't change.
HTML
<nav class="clearfix">
home
about us
tour
flickr search
<div class="rightnav">
Sign Up
Log In
</div>
</nav>
CSS
.greybackground {
background: #E6E6E6;
}
JS
$('nav a').on('click', function(){
$('nav a').removeClass('greybackground');
$(this).addClass('greybackground');
});
If you are creating multi page website and want to change link color on each page, simply create a class with specific css properties and add this class to respective navbar link on each page. Make sure that on any page, class must be added to only respective page link.
Any if you are looking solution for single page website following code will work just fine
Here is html css code for simple navigation bar
<h1>navbar</h1>
<li>Home</li>
<li>Products</li>
<li>About us</li>
<li>Contact</li>
<button>Log in</button>
</ul>
a{
background-color:black;
padding:10px;
text-decoration:none;
color:white;
}
li{
margin:30px;
display:inline;
}
ul{
list-style-type: none;
}
.transform{
background-color:red;
}
button{
background-color:green;
padding:10px;
color:white;
}
This is javascript to change bg color of active link
$("a.link").click(function(){
$("a.link").css("background-color", "black");
$(this).css("background-color", "red");
});
Simply add class '.link' for every navbar link and when user clicks on any navbar link css property ad applied to that link and all other links will change their bg color to none. I hope it helps
https://codepen.io/pranjalkoshti/pen/GMarvj
The easiest way to achieve this is identify an element that
Is present on every page
You can add markup to
For example, a div for your overall content.
If you add the following to the div :
<div id="content" data-currentpage="about">
This will identify the page uniquely.
and for each menu item add a class that matches:
<li>Home</li>
<li>Products</li>
<li>About us</li>
<li>Contact</li>
So, on page ready ( jQuery(document).ready(function(){...) run the following code:
// -- Find the pages 'data' tag --
var currentPage = jQuery('#content').data('currentPage');
// -- Add a dot to turn it into a class identifier --
currentPage = '.' + currentPage;
// -- Add a background class to to the menu item with that class --
jQuery(currentPage).addClass('greybackground');
This will 'match' each page (via the data-currentpage tag) to the corresponding menu item and add your background class to that menu item.
Solution in vanilla JS (HTML, CSS).
Navbar items need to be in class .navlinks
Add styling under the class current-link.
<html>
<nav>
<ul>
<li class="navlinks"></li>
<li class="navlinks"></li>
</ul>
</nav>
</html>
<style>
.current-link {
background-color: red;
}
</style>
<script>
let links = document.getElementsByClassName("navlinks");
for(let i = 0;i < links.length;i++){
if (links[i].href.replace(/\/$/, '') == ocument.URL.replace(/\/$/, '')){
links[i].classList.add("current-link");
}
}
</script>

How to open a new jsp page with JavaScript

I have the following dropdown menu how can i redirect each menu to corresponding page by clicking each of menu? is it possible by using one javascript function if yes how?
thanks in advance...
<div>
<ul>
<li id=home onclick="show(this.id)">Home</li>
<li id=collection onclick="show(this.id)>Collection</li>
<ul>
<li id=men onclick="show(this.id)>Men</li>
<li id=women onclick="show(this.id)>Women</li>
</ul>
<li id=contact onclick="show(this.id)>Contact</li>
</ul>
</div>
Yes you can.
Use window.open("URL") in your case URL is this.id
Also you can update window.location
read more here http://www.tizag.com/javascriptT/javascriptredirect.php
Like Niko said you need closing quotes
.. onclick="window.open(this.id)" ..
If you only need o JS function to redirect based on a parameter that, in your case, is the component ID, this will do the work:
<script type="text/javascript">
var show = function(id) {
window.location.href = id + '.jsp';
};
</script>
If you want to navigate DOM and get link's href attribute use:
document.getElementById(id).firstChild.href
Considering that the first element inside the component referred by ID is a link tag.
Try this?
$("div > ul li a").click(function() {
window.location.href += "/" + $(this).parent()[0].id;
});
I tried to use a selector that didn't modify your HTML, so that's why it looks so icky.
This makes no sense.
I understand that your particular functional requirement is to invoke the link when the enduser clicks somewhere in the space of the <li> outside the link. To achieve that just set the CSS display property of the <a> element to block. This way the link will span the entire space of its parent element.
<ul id="menu">
<li>Home</li>
<li>Collection</li>
<ul>
<li>Men</li>
<li>Women</li>
</ul>
<li>Contact</li>
</ul>
with this CSS
#menu li a {
display: block;
}
No need for ugly JavaScript hacks. Opening a new JSP page location in the current window is by the way to performed by window.location = 'some.jsp';. But this is not necessary if you use the right solution for the concrete problem. In the future questions, try to elaborate more about the functional requirement instead of concentrating only on the solution of which you thought that it's the right solution for the particular functional requirement.

inner span is not getting ref in jQuery.Why?

I have one html structure:
enter code here <ul>
<li><span>aaa</span>
<div>
<ul>
<li><span>bbb</span> </li>
</ul>
</div>
</li>
<li><span>ccc</span>
<div>
<ul>
<li><span>ddd</span> </li>
</ul>
</div>
</li>
</ul>
now what should be the exact code to access
<span>aaa</span>and <span>ccc</span>
but not span with bbb and ddd...I have used $("li span:first-child") and its working fine..is it rite I mean as per standard...bcoz I think it should ref every first child span under any li inside that html file....what should be the exact code?
This maybe because you are nesting li without ol/ul, li should be inside ol/ul not inside another li
Your HTML is not well formed. li elements aren't closed. This could be causing the problem.
So you want all the <span>s which are a direct child of an <li> which has a nested list inside it? Here's my go at it:
$("li:has(ul) > span")
Explanation, step by step:
li // find all <li>s
:has( // which have inside them
ul // a <ul> tag
) // (current context is still at the <li>
> // now find just immediate children (not grandchildren, etc)
span // ..which are spans
The result set should now be a list of <span>s whose parent is an <li> which has a <ul> descendant.
Pay a visit to http://validator.w3.org/. Browsers do amazing things in trying to build a DOM from illegal markup, but the results are often not what you expect and inconsistent across browsers.
Use correct markup — then worry about tools dealing with it in unexpected ways. See GIGO.

Categories