Vanilla Javascript click on LI that contains a certain text - javascript

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>

Related

Trying to add class to parent of parent

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.

Javascript each() function remove link

I've got a website under prestashop, and my dropdown menu has different categories that are all clickable. I would like to remove the links from the "Marques" and "Les Gammes" categories and leave just the text. I'm using the each() function to select all my categories, but this returns an array within the li and the ul inside the li.
Here is the JSFiddle.
Here is the js code:
$('jms-mega-menu').ready(function () {
// Get each div
$('.notlink').each(function () {
// Get the content
var str = $(this).text();
$(this).html(str);
});
});
And here is a sample of my html code. You can find the full code on the fiddle.
<ul jms-mega-menu>
<div>
...
<ul class="mega-nav level1">
<li class=" haschild group notlink"><a id="item-8" href="#">Marques</a>
<ul>
<li><a id="item-9" href="#">Apple</a></li>
<li><a id="item-10" href="#">Samsung</a></li>
</ul>
</li>
</ul>
<ul>
...
One solution would be use unwrap to remove the a tag from around the text. Note the use of .notlink > a to only affect anchors that are direct children of the .notlink and not the nested lists:
$('.notlink > a').contents().unwrap();
http://jsfiddle.net/orvrj7qs/5/
Another option which may be a bit more extensible would be to use replaceWith, which would allow you to make additional modifications to the text if needed:
$('.notlink > a').replaceWith(function(){
return $(this).text();
});
In this case, we simply replace the anchor with just the text within the anchor.
http://jsfiddle.net/orvrj7qs/6/

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

Add a space between ul and li element created by JavaScript

Been struggling with a problem now.
I have a list that behaves quite weird, and couldt find the problem until i firebugd it and saw that the entire file prints out in one row.
something like this.
<div class="clock-content-wrapper"><ul class="clock-digit-wrapper hour"><li class="clock-digit-one"></li><li class="clock-digit-three"></li></ul><ul class="clock-digit-wrapper minute"><li class="clock-digit-three"></li><li class="clock-digit-seven"></li></ul><ul class="clock-digit-wrapper second"><li class="clock-digit-zero"></li><li class="clock-digit-zero"></li></ul></div>
There is no spaces between the elements.
Now i didn't know that could be a problem so i started to fix the elements in firebug like this.
<div class="clock-content-wrapper">
<ul class="clock-digit-wrapper hour">
<li class="clock-digit-one"></li>
<li class="clock-digit-three"></li>
</ul>
<ul class="clock-digit-wrapper minute">
<li class="clock-digit-three"></li>
<li class="clock-digit-seven"></li>
</ul>
<ul class="clock-digit-wrapper second">
<li class="clock-digit-zero"></li>
<li class="clock-digit-zero"></li>
</ul>
</div>
And notice that if i have the </ul> element under my </li> the script actually works at it supposed to.
Is there a way to structure the file with javascript ?
I have a jsFiddle, where you can se the differens between the tree created in HTML and the one with JavaScript.
http://jsfiddle.net/Xk49c/
I really dont want to change anything in the css . since both html and js application is using the same css .
Your <ul> elements are displayed as inline-block in your fiddle. I suspect they are suffering from this little-known feature of inline-block.
The problem is, when you create the elements using HTML, you indent or separate the elements with one or more spaces, or even new lines. HTML renders these spaces as ONE single space and so you see the space between those elements.
To add spaces between elements created by JavaScript, either you ll have to add a padding left to minute and second class, or insert a text node between each UL
hours = createElementWithClass('ul', 'clock-digit-wrapper hour');
clock_toolbar_wrapper_close.appendChild(hours);
clock_toolbar_wrapper_close.appendChild(document.createTextNode(' ')); // Add this
minutes = createElementWithClass('ul', 'clock-digit-wrapper minute');
clock_toolbar_wrapper_close.appendChild(minutes);
clock_toolbar_wrapper_close.appendChild(document.createTextNode(' ')); // And this

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