Closest function in jQuery and extracting the elements - javascript

I have a html fragment as follows:
<div id="samplediv">
<ul>
<li name="A">
<a id="A">
</li>
<li name="B">
<a id="B">
</li>
</ul>
</div>
I have a text called:
var text = "B";
I have want to check if the text matches with any of the elements of li and add a class name "disable" for the anchor element not matching with text.
I my case I want to add a class called "disable" for
<a id="A">
This is what I have tried:
$("#samplediv li").each(function() {
if($(this).name != text){
$(this).closest("a").addClass("disabled");
}
});
But the thing here is $(this).name is evaluating to "undefined" . What is it that I am missing?
Edit: Due to typo ,had missed the tag

There are multiple issues,
$(this) returns a jQuery object which does not have name property, instead you can use $(this).attr('name')
.closest() is used to find the ancestor element, but the a is a descendant of the li element, so you need to use find()
You can find all the li elements which does not have the given name and then find the a element within it like
var text = 'B';
$("#samplediv li").not('[name="' + text + '"]').find("a").addClass("disabled");
a.disabled {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>

var text = "B";
$("#samplediv li").filter(function() {//use filter
return $(this).attr('name') != text;//use .attr() to get name attribute
}).find('a').addClass("disabled");//use find to get the anchor tag
.disabled{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="samplediv">
<ul>
<li name="A">
<a id="A">a</a>
</li>
<li name="B">
<a id="B">b</a>
</li>
</ul>
</div>
Use .filter()
Description: Reduce the set of matched elements to those that match the selector or pass the function's test.

Related

Get <li> value based on class

I have the following example code:
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
When a specific <li> is selected, the class changes to whatever the name is, plus sortUp or sortDown.
Example:
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
I am trying to get the value of the actual text inside the <li>, but I keep getting undefined.
var li = document.getElementById('TEST');
alert($('#TEST').filter('.sort').html());
I tried using different ways but no matter what I do I can't get the actual value, which in this case should be 222.
Any idea what I am doing wrong?
You can select the li with either sortUp or sortDown by using the [attribute*="value"] selector,
The [attribute*="value"] selector is used to select elements whose
attribute value contains a specified value.
const li = document.querySelector('[class*="sort"]');
console.log(li.textContent);
li.style.background = "red";
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
See css attribute selectors
I'm not sure what the classes have to do with your requirement to get the text of the clicked li element. Just set up a click event handler on the ul and then in the handler, check the event target to ensure it was an li, then just get the text of the event target.
document.getElementById("TEST").addEventListener("click", function(evt){
if(evt.target.nodeName==="LI"){
alert(evt.target.textContent);
}
});
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
Maybe you can try this:
alert($('#TEST').find('li[class^='sort']').html());
You will find a li element that has a class that starts with "sort".
You can see more of this selector here.

Trying to get the value of very next element of the current selected element using jQuery

I am trying to get the value of very next element of the current/selected element for example here is the list
<ul>
<li class="abc selected">test </li>
<li class="abc">test1 </li>
<li class="abc">test2 </li>
</ul>
From the above code I am trying to get the value of "a" tag which is very next to the selected li, in above case I am try to get the value of a tag which is test1 and this "a" tag is within the very next li after the selected one.
I tried to use the jQuery below but its fetching the empty result. Any help
var linktext1= jQuery(".selected").next("li a").text();
alert (linktext1);
The selector string passed to .next will filter out the next element if it doesn't match the selector string. But the next element is a li, not an a, so .next('li a') won't work.
Use .next("li").find('a') instead:
var linktext1 = jQuery(".selected").next("li").find('a').text();
console.log(linktext1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="abc selected">test </li>
<li class="abc">test1 </li>
<li class="abc">test2 </li>
</ul>
In this particular situation, though, there's no need for a li selector to pass to .next, because what is .selected will be a li, so any of its siblings will also be lis:
var linktext1 = jQuery(".selected").next().find('a').text();
console.log(linktext1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="abc selected">test </li>
<li class="abc">test1 </li>
<li class="abc">test2 </li>
</ul>
I think you should remove "li a" and it works. Below is the code
var linktext1= jQuery(".selected").next().text();
alert (linktext1);
Here is the example jsfiddle

querySelector() where display is not none

I have a long list of <li> items I need to filter. I want the visible ones. Here's an example hidden one:
<li style="display:none;"
<a href="https://www.example.com/dogs/cats/">
<img class="is-loading" width="184" height="245"
</a><span>dogscats</span>
</li>
Those which are not hidden don't have a display visible attribute, they just don't have a style attribute at all.
This gives me the opposite of what I want:
document.querySelectorAll('.newSearchResultsList li[style="display:none;"]')
How can I select based on style attribute does not equal or contain "display:none;"?
This whole thing is kind-of hacky, but you could use the :not() selector to invert your selection. Beware some browser normalize the style attribute, so you will want to include a selector for the space that may be normalized in.
var elements = document.querySelectorAll(
'.newSearchResultsList li:not([style*="display:none"]):not([style*="display: none"])'
);
console.log(elements);
<ul class="newSearchResultsList">
<li style="display:none;">hidden 1</li>
<li style="display:block;">visible 1</li>
<li style="display:none;">hidden 2</li>
<li style="display:block;">visible 2</li>
</ul>
If you want you could also select both these elements and any child elements.
const selector = '.newSearchResultsList li:not([style*="display:none"]):not([style*="display: none"])';
const elements = document.querySelectorAll(`${selector}, ${selector} *`);
console.log(elements);
<ul class="newSearchResultsList">
<li style="display:none;">hidden <i>1</i></li>
<li style="display:block;">visible <b>1</b></li>
<li style="display:none;">hidden <i>2</i></li>
<li style="display:block;">visible <b>2</b></li>
</ul>
Of course, these only work when selecting elements with inline styles.
Try this:
document.querySelectorAll('.newSearchResultsList li:hidden')
or (EDIT: Based on style attribute) Note that a simple SPACE destroys the selector. I mean: "display:none" can not be "display: none"
document.querySelectorAll('.newSearchResultsList li[style*="display:none"]');
or opossite
document.querySelectorAll('.newSearchResultsList li:not([style*="display:none"])');
Use '.newSearchResultsList li' selector to select all the li elements
Use Array#filter over collection
Use getComputedStyle to get all styles associated with element
Return only those elements having style !== none
var liElems = document.querySelectorAll('.newSearchResultsList li');
var filtered = [].filter.call(liElems, function(el) {
var style = window.getComputedStyle(el);
return (style.display !== 'none')
});
console.log(filtered);
<ul class="newSearchResultsList">
<li style="display:none;">
<a href="https://www.example.com/dogs/cats/">
<img class="is-loading" width="184" height="245">
</a><span>dogscats</span>
</li>
<li>
<a href="https://www.example.com/dogs/cats/">
<img class="is-loading" width="184" height="245">
</a><span>Visible</span>
</li>
</ul>

How to get specific element javascript based on style

I need to acces an element that has a certain style.
This is my structure
<ul>
<li> Hi </li>
<li> bye </li>
<li> third one </li>
</ul>
The list items are placed on top of each other (last one first) and I can dislike something or like something. Once I do that, it gets a style display:none like following:
<ul>
<li> Hi </li>
<li> bye </li>
<li style:"display:none;"> third one </li>
</ul>
Now after I did that I want to be able to acces the last element that does not have display:none, (the bye) how can I do this?
I was thinking of something in the form of:
var myId = $("#slider > ul li").last().attr("id");
But obviously I always get the ID of the item that is hidden since its still there.
Can I do something like select last where !display:hidden ?
Can I do something like select last where !display:hidden ?
Yes, with jQuery's :visible pseudo-class:
var myId = $("#slider > ul li:visible").last().attr("id");
(Note: Your li elements don't actually have id values, but that's a tweak.)
Live Example:
var listItem = $("#slider > ul li:visible").last();
$("<p>")
.text("Text of last visible item: " + listItem.text())
.appendTo(document.body);
<div id="slider">
<ul>
<li>Hi</li>
<li>bye</li>
<li style="display:none;">third one</li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Can use ':visible' selector
var myId = $("#slider > ul li:visible").last().attr("id");
It should work using:
$("#slider > ul li:visible").last().attr("id");
https://api.jquery.com/visible-selector/
so your inline styling is a bit off it should be
<ul>
<li> Hi </li>
<li> bye </li>
<li style="display:none;"> third one </li>
</ul>
You could do a few different things, best is probably just iterate through and check for where display = none, then go to the previous element:
$('ul').children().each(function(e) {
if($(this)[0].style.display == 'none') {
console.log($(this).prev());
}
})

Find <li> tag by its child tag <a> href value

How to find Li tag which has a child tag by its Href value. By this I need to set class for that li tag.
My HTML
<div id="tabs" class="tab_wrapper">
<ul class="nav nav-tabs">
<li>Subject
</li>
<li>Contract
</li>
<li>Neighborhood
</li>
<li>Site
</li>
<li>Improvements
</li>
<li>Supplemental Data
</li>
</ul>
</div>
Css
.Active
{
color:red;
}
For example I have to set class "Active" for li tag which has href value "#tabNeighbourhood", so that li tag will be like
<li class="active">Neighborhood
</li>
Using :has() selector:
$('li:has(a[href="#tabNeighbourhood"])').addClass('active');
This will add class active to any LI containing anchor with specific href attribute.
Use .parent() :
$("ul.nav > li").removeClass("active"); // Clear all li's class attributes.
$("a[href='#tabNeighborhood']").parent().addClass("active"); // Add active to neighborhood.
$('li', '#tabs')
.filter(function() {
return !! $(this).find('a[href="#tabNeighbourhood"]').length;
})
.addClass('active');
I refer you to the official docs for explanation of the single parts.
Try Below Code
$(document).ready(function(){
$('body').find('a').each(function(){
if($(this).attr('href')=="#tabNeighbourhood"){
$(this).closest('li').addClass("Active");
}
});
});
Using your HTML structure you can use an immediate children selector >, has selector and a selector on href attribute.
Code:
$('#tabs>ul>li:has(a[href="#tabNeighbourhood"])').addClass('active');
Demo: http://jsfiddle.net/swvzot7f/
Try it by yourself. Here is an algorithm if you consider it too complex:
Search for needed <a> by attribute.
Select the parent of <a> that was found.
Add class to that parent.
Answer is pretty simple, so I do think it is much more important to show you the way of thinking instead of feeding with ready made-up solution.
EDIT
Just in case you fail I decided to add a solution too:
$( "a[href='NEEDED HREF TO SEARCH']" ).parent().addClass('active');
Another option, You can achieve by CSS alone:
a[href$='#tabNeighbourhood']
{
color:red;
}
Fiddle
JQuery method (using :has() selector):
$('ul li:has(a[href="#tabNeighbourhood"])').addClass('Active');
Fiddle
The following code (vanilla js :-) shows you how to add a class to an HTML element which ha specific href value. Just enter in the field the href value you want to search, it will add a class active, example try: #tabSubject or #tabImprovements. I hope it is what you need.
function setActive(){
var elm = document.getElementsByName('findElm')[0],
searchElm = elm.value,
targetStr = 'a[href*="' + searchElm + '"]',
target = document.querySelector(targetStr);
target.classList.add('Active');
}
.Active
{
color:red;
}
<div id="tabs" class="tab_wrapper">
<ul class="nav nav-tabs">
<li>Subject
</li>
<li>Contract
</li>
<li>Neighborhood
</li>
<li>Site
</li>
<li>Improvements
</li>
<li>Supplemental Data
</li>
</ul>
</div>
<input type="text" name="findElm" value="#tabImprovements"><br>
<input type="submit" value="Search" name="submit" onclick="setActive();">
css: Use the nth-child concept(Best Practice)
.tab_wrapper ul :nth-child(3) a {
color:red;
}

Categories