How to use CSS selector not to exclude span text - javascript

I'm having some problems figuring out how to use the :not selector correctly.
I have a menu which contains menuitems, where one menu-item has an "is-selected"class to show the user what the current page is that he is visiting.
I would like to retrieve the text of this item, without the badge.
Div Structure
<div class="a-TreeView-content is-selected is-current--top">
<a class="a-TreeView-label">
Orderinvoer
<span class="cb-Menu-badge">25</span>
</a>
</div>
And the following code:
var activeMenuItem = $('div.a-TreeView-content.is-selected > a').text();
Which returns something like: "Orderinvoer25"
I've tried the following to retrieve only the text 'Orderinvoer' but I don't really know what I'm doing wrong:
$('div.a-TreeView-content.is-selected > a span:not(".cb-Menu-badge")').text()
$('div.a-TreeView-content.is-selected > a :not(span)').text()
$('div.a-TreeView-content.is-selected > a:not(".cb-Menu-badge")').text()
$('div.a-TreeView-content.is-selected :not(".cb-Menu-badge")').text()

You can use replace() to remove the .cb-Menu-badge text and trim() to remove extra space.
Stack Snippet
var activeMenuItem = $('div.a-TreeView-content.is-selected > a').text().replace($('.cb-Menu-badge').text(), '').trim();
console.log(activeMenuItem);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a-TreeView-content is-selected is-current--top">
<a class="a-TreeView-label">
Orderinvoer
<span class="cb-Menu-badge">25</span>
</a>
</div>

Try this
$('div.a-TreeView-content.is-selected > a')
.clone()
.children()
.remove()
.end()
.text();
FIDDLE HERE
.clone() clones the selected element.
.children() selects the children from the cloned element
.remove() removes the previously selected children
.end() selects the selected element again
.text() gets the text from the element without children

Pick the first text node in .is-selected a.
$(".is-selected a").contents().get(0).nodeValue
var selected = $(".is-selected a").contents().get(0).nodeValue;
console.log(selected);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a-TreeView-content is-selected is-current--top">
<a class="a-TreeView-label">
Orderinvoer
<span class="cb-Menu-badge">25</span>
</a>
</div>

By using :not() selector, you are trying to select an anchor tag which is not a span type or not having cb-Menu-badge class. So, it always select the anchor tag and gives you the text it has inside. You can be leaving the span inside the anchor tag by selecting its first content alone as follows. Read more about contents()
$($('div.a-TreeView-content.is-selected > a').contents()[0]).text();
The above link has lot more examples which will help you if you have your text inside like 'text1<span>text2'

Related

Get <li> text number using jquery

i am trying to get li tag text value using js but i am not getting the expected output
i.e ("Pens").
I have added a code snippet.
Note - I cannot change html.
console.log(jQuery('#accordionItem li span').html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
Any thoughts on this ?
Use the text method like below:
console.log($('#accordionItem li span').text());
from what I understand you want the text of the li without the text of the span.
So you can use the replace function to do it like so:
console.log($('#accordionItem li').text().replace($('#accordionItem li span').text(), ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
if you want a more general solution that will get you just the text of the li without any of its children that would be a better solution:
console.log($('#accordionItem li').contents().get(0).nodeValue);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>
You seem to be selecting the <span> tag on your jQuery selector.
Although I'd suggest using the text method to achieve what you are looking for.
No jQuery needed.
Since you have an element with ID, you can access it directly, and get the node's text and simply remove any non-digit characters, and you'll be left with the numeral value you are after.
The benefit of this method is the irrelevance of the DOM structure - it will always work for that element (with that ID), but can be applied to any <li> element, regardless if it has a <span> child (or any other children)
console.log(
accordionItem.children[0].firstChild.textContent
)
<div id="accordionItem" class="filter_middle-stage2-list_wrapper">
<li style="font-weight: bold;">Pens<span>(1200)</span></li>
</div>

How to select the last child inside the tree using jQuery?

Suppose I have such a structure:
<div id="content">
<div>
<span>
<b>
<i>
<u>
<span>Price</span>
</u>
</i>
</b>
</span>
</div>
</div>
In this case, the number of tags inside the div #content and which ones they don't know me. I only have access to the id content.
How do I get the selector to the latest span which contains the text Price?
p.s. lastChild method returns the last child within the selected selector, but not deeper!
Select all children of #content using * selector and use .filter() to filtering element. In callback filter elements hasn't any child.
$("#content *").filter(function(){
return $("*", this).length == 0;
});
// Or using ES6
$("#content *").filter((i,v) => $("*", v).length == 0);
var ele = $("#content *").filter((i,v) => $("*", v).length == 0);
console.log(ele[0].outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div>
<span>
<b>
<i>
<u>
<span>Price</span>
</u>
</i>
</b>
</span>
</div>
</div>
You can use .find():
https://api.jquery.com/find/
This will recursively look for your selector, so:
$('#content').find('span') will give you two spans, one for the first nested span and one for the second nested span. The downside is that if you have multiple spans you'll need to find the right one.
If you can put an identifier in the last one, say a class named 'target-class', than you know you'll find the right one:
$('#content').find('span.target-class');
First of all let's fix your syntax. You can't put an <span> directly within a <u>. You need a <li> node. Also you can't/shouldn't put block elements such as ul within inline elements (span, a, b, i...). And even <b> and <i> are not recommended, better use semantic markup such as <strong> or <em> instead.
Now your problem. I think you don't have to care about being the last node. If you know the text contained is "Price" you can look for it in the following way:
var selector = $('#content').find(":contains('Price')");
$(selector).addClass('highlighted');
.highlighted {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<div>
<u>
<li>
<span>Price</span>
</li>
</u>
</div>
</div>
If this solution does not fits your needs, to get the last node you have to get all of them an check if they have children or not. Once they don't, you've reached your target.
But I have to say that this is a solution you could have found in SO.
Select deepest child in jQuery
Jquery Way -
You could target all spans $() and target the latest span using slice() method.
$('#content span').slice(-1)[0];
Javascript way -
Find all spans using querySelectorAll(), You'd get a NodeArray, you can convert it to Array using Array.from() and slice() last item from it which is latest span.
Array.from(document.querySelectorAll('#content span')).slice(-1)[0]

Trouble using .closest function

I'm trying to make a sidebar menu for a dashboard. I want to implement this with .closest as it will fit with my code right. Here is a simple example of what I'm trying to do: https://jsfiddle.net/eu8kjzh4/10/
Why isn't the closest span's (and the only span in this case) text being replaced with a '-'? In my code, I have
$('.' + Key).closest( '.' + Key ).css("color", "#000");
This code works just fine, but the one in the jsfiddle does not.
closest traverses up the DOM and is used for nested elements.
In your markup, your div is not a descendant of your span, not even a sibling.
You have
1. To retrieve the previous sibling (the first li after the body)
2. And find the span inside the li
$(document).ready(function() {
$(".sub").prev().find('span').text('-');
});
Also, in your fiddle, you forgot to include jQuery.
Here is a working code : https://jsfiddle.net/qwc6pepr/1/
Incorrect function: .closest( selector ) Returns: jQuery
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
What you want is the prev which finds the first sibling prior to the element
$(document).ready(function() {
$('.sub').prev('li').find('span').text('-');
});
From jQuery documentation
Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements
Your span is neither a Parent Element of your div.sub in the DOM, nor matches with the $(".sub") rule.
The only way to make your jQuery code work with your HTML structure :
$("#plusMinus1").text("-");
Or modify your HTML structure to match with the .closest() method requierements
Fiddle
When you go to the parent you'll end up in the body. From there you can find the span.
$(document).ready(function() {
$(".sub").parent().find("span").text("-");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
<li>
<a class="selected" href="#" onclick="return false;">Dashboard 1 <span id="plusMinus1">+</span></a>
</li>
<div class="sub">
<ul>
<li><a id="s1" href="">Test A</a>
</li>
<li><a id="s2" href="">Test B</a>
</li>
<li><a id="s3" href="">Test C</a>
</li>
</ul>
</div>
</body>

How can I use JQuery to select the first div element inside a container element?

I am pretty new in JQuery and I have the following situation:
<!-- Bottone relativo ai progetti WIFI: -->
<a title="WIFI" href="javascript: void(0)" id="showWifi_${item.index}" class="showWifi">
<div class="news_box news_box_01 hvr-underline-from-center " style="margin-right: 50px;"></div>
</a>
I have the a tag having class="showWifi".
I have to use JQuery to select the first div element inside this a tag having class="showWifi".
I don't want set an id to this tag, but I want use the JQuery syntax to select the first div tag
How can I do this?
You can use first()
$('a.showWifi div').first().addClass('something')
You can also use :first pseudo-selector
$('a.showWifi div:first').addClass('something')
Note: first() is faster than :first(Thanks to #Zeratops). See: jQuery :first vs. .first()
You can use :first
Selects the first matched element.
$('a.showWifi > div:first')
Use .first()
$(".showWifi").find("div").first();
Working JSFIDDLE: http://jsfiddle.net/uamkvdkr/

Method to select matching data elements using jQuery

I'm new to jQuery and have a question that goes beyond my knowledge. I have a link with a unique data-number and a div with a matching data-number. The goal is to hide all divs and when each link is clicked by the user the div would be displayed with the matching data-number.
The part that's difficult for me to figure out is how to iterate through all of the links and divs matching them up so when each link is clicked ONLY the matching div with the same data-number will be displayed.
Here is what I have so far in Coffeescript:
$('#task-item').on('click', (event) ->
n = $(#).data('number')
if (n > 0)
event.preventDefault()
$('#task-info').fadeToggle(600)
)
Sample html link:
<li id="task-item" data-number="3">
<span class="label label-purple"> Task</span>
<i class="icon-angle-right"></i>
<span class="label label-success">Open</span>
NEW SAVE METHOD FOR TASKS
..... additional HTML....
</li>
Sample div html:
<div id="task-info" data-number="3" class="span8">
..... #MORE HTML HERE ....
</div>
If there is a better way to accomplish this I'm open to any suggestions.
Firstly, I assume the li and div in your example are repeated multiple times, so you should be using a class to identify them. Secondly, you can use filter to find the element by the required data attribute. Try this:
$('.task-item').on('click', (event) ->
var $item = $(this);
$('.task-info').filter(function() {
return $(this).data('number') == $item.data('number');
}).fadeToggle(600);
Look into jQuery attribute selectors
http://api.jquery.com/attribute-equals-selector/
You should be able to select the div you want like this:
$("div[data-value='3']")
First thing I would recommend is change the li ids to class like <li class="task-item">
Then
<div class="task-info" data-number="3" class="span8">
JS
$(".task-item").click(function(e){
var itemNumber=$(this).data('number');
$('.task-info').filter(function() {
return $(this).data('number') == itemNumber
}).fadeToggle(600);
});

Categories

Resources