.text() not returning value - javascript

I'm using this code to create a <ul><li> of the classes attached to the div .lista-produtos.
$(document).ready(function(){
var alts = {};
$('.lista-produtos').each(function(){
var classes2 = $(this).attr('class').split(' ');
for (var i = 0; i < classes2.length; i++) {
var matches2 = /^tipo\-(.+)/.exec(classes2[i]);
if (matches2 != null) {
var produto = matches2[1];
}
}
if(!alts[classes2]){
alts[classes2] = true;
$('ul.filters').append('<li class="filter-produto">'+ produto +'</li>');
}
});
});
The code above generates <li>s inside of the <ul class="filters">. So the code is something like this:
<ul class="filters">
<li class="filter-produto active">Produto 1<li>
<li class="filter-produto">Produto 2<li>
<li class="filter-produto">Produto 3<li>
<li class="filter-produto">Produto 4<li>
</ul>
As you can see, one of the <li>s will have an additional class named "active", and the problem is I need to get the text inside of it (Produto 1) to use on another code but it's not working:
var produto2 = $('li.filter-produto.active').text();
I tested alert(produto2); to see if the code worked but it only returns a blank value and not the text inside the <li>.

Sadly I don't have rep to comment, but can you show us the order of the stuff happening?
Perhaps you are asking for the value before the active class it attached to the li. Something like this:
// Function to create the ul and lis
var produto2 = $('li.filter-produto.active').text();
// Function that adds the active class
So maybe the li.filter-produto.active doesn't exist when you ask for it's value?

Related

How to set both a and href to an existing list?

I already have a navigation bar and I would like the first item to become a link. I have only succeeded to append a link to the already existing item of the list. I feel like I should use the .setAttrribute method instead but I can't figure out how. Would someone help me so I can end up with a link instead of an list item AND a link?
<nav>
<ul>
<li class="navigation">HTML</li>
<li class="navigation">DOM</li>
<li class="navigation">Javascript</li>
</ul>
</nav>
function newLink () {
var navigation = document.getElementsByClassName("navigation");
var existingText = navigation[0].innerHTML;
var a = document.createElement("a");
a.setAttribute("href", existingText);
a.innerHTML = existingText;
document.getElementsByClassName("navigation")[0].appendChild(a);
}
newLink();
Why you making it so complicated? this just using innerHTML
function newLink () {
var navigation = document.getElementsByClassName("navigation");
var existingText = navigation[0].innerHTML;
document.getElementsByClassName("navigation")[0].innerHTML= ''+existingText+'';
}

How can I properly convert the following Jquery to pure Javascript?

How can I convert the Jquery below to pure JavaScript?
var $buttons = jQuery("#thePaginator li a");
for (var index = 0; index < $buttons.length; index++) {
var $button = $buttons.eq(index);
$button.click(function() {
var newPage = $(this).data("page");
jQuery("#attribute-myAttribute").val(newPage);
jQuery("#update").click();
});
}
I wouldn't normally ask a question like this, but the conversion has been difficult, especially with the event listener. Here is what I have so far:
runPaginate();
function runPaginate(){
var buttonArray = document.getElementById("paginator_TCC").querySelectorAll('li');
for(i=0;i<(buttonArray.length);i++){
buttonArray[i].addEventListener('click', runUpdate);
}
}
function runUpdate(){
console.log("runUpdate started")
// will need to add code in here for update
}
update (in Jquery) is a method that is called to update attributes on the page. Consider the runUpdate function to suffice for that method call.
I believe that I'm having so much trouble because I'm dealing with HTML Collection, so when I get the li elements (which are actually buttons) I can't seem to add an event listener to them. Below is the inspection result from Dev Tools:
<div id="thePaginator" class="simple-pagination">
<ul>
<li class="disabled">
<span class="current prev">Prev</span>
</li>
<li class="active">
<span class="current">Year 1</span>
</li>
<li class="disabled">
<span class="current next">Next</span>
</li>
</ul>
</div>
Any assistance is appreciated.
I'd use a for...of loop, and move the callback into the loop. That way you can access the iterator:
for(const button of buttonArray){
button.addEventListener('click', function runUpdate() {
const { data } = button.dataset;
//...
});
}
This is the JS equivalent of your jQuery (this just replaces the jQuery method calls with their equivalent JS method calls)
var buttons = document.querySelectorAll('#thePaginator li a');
for(var index = 0; index < $buttons.length; index++) {
var button = buttons[index];
button.addEventListener("click", function(evt) {
var newPage = this.dataset.page;
document.getElementById('attribute-myAttribute').value = newPage;
document.getElementById('update').click();
})
}

Is there any programmtical way where I can remove class of list item

I am doing one loop where I am matching with some value and assigning class="hidden" to list. But When I run again the loop I want all my list should be without class, so I can assign for other value.
Here is my code.
for (i = list.children.length; i--;) {
li = list.children[i];
match = li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1;
li.classList.toggle('hidden', !match)
}
But before I run this loop I want all the list without any class so hete in the list I want to remove Class="hidden"
<li class="hidden">
Albania
</li>
Can anyone help me to achieve this
You want to do this before your existing loop? Try this:
var list = document.getElementById("list");
for (i = list.children.length; i--;) {
li = list.children[i];
li.classList.remove("hidden");
}
<ul id="list">
<li class="hidden">foo</li>
<li>bar</li>
<li class="hidden">baz</li>
</ul>
Though it does look like you could do this in the beginning of your existing loop. No need for another loop before that one.
Why not use a combo of Element.classList.contains(), ..remove(), ..add() etc. Lots of info on the MDN page.
For example:
for(i=list.children.length; i--;) {
li = list.children[i];
if (li.textContent.toLowerCase().indexOf(value.toLowerCase()) > -1) {
li.classList.add('hidden');
// or is it li.classList.remove('hidden'); here?
}
}
It is safe to ..add() even if the element has the class already. The class will not be added twice.

jquery select by class then match value

I have a list like this
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
then I have a value like this
var myvalue = 1;
I want to compare myvalue with all the $(".somename).text() to find the matching ones and change the text of the matching to something else like below
<ul>
<li class="somename">changed</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">changed</li>
</ul>
$(".somename").text() give me all the text in a string like 1231
and I tried to for loop
for(i=0;i<$(".somename").length;i++){
if(myvalue == $(".somename")[i].text()){
$(this).text("changed")
}
}
$('.somename').each(function() {
var value = $(this).text();
if (value == "1") {
$(this).text("Changed")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
Use .each() to loop through all elements with the class.
Have a condition , if met change the text
When using the bracket object property accessor ([]) on a jQuery object you are accessing the underlying object in the collection so .text() would not be available as that is not a function on the underlying DOM object (you should have seen an error on your console)
You can use jQuery .each method to loop through the collection
$(".somename").each(function(){
//unless you are going to be doing more jQuery DOM stuff
//no need to wrap in jQuery just access the innerText
if(myvalue == this.innerText){
this.innerText = "changed";
}
});
If you dont want to use the .each method and just use the for loop you would need to use either .eq or similar method to get the jQuery wrapped object at a particular index
var elements = $(".somename");
for(i=0;i<elements.length;i++){
let element = elements.eq(i);
if(myvalue == element.text()){
element.text("changed");
}
}
Do like this...
$(".somename").each(function(e, val ){
if (myvalue == e.text){
//do stuff here
}
));
Please try this out but FYI I've not tried this on my own system.
var myvalue = 1;
var lists = document.getElementsByTagName('li');
for(var i = 0; i < lists.length; i++){
if(myvalue == lists[i].innerHTML){
//change your text here
}
}
You can use jQuery .each function.
var myvalue=1;
$('.somename').each(function(){
if($(this).text()==myvalue){
$(this).text('changed');
}
});
Few things here
1. When you search any DOM element .Try to copy it into a variable and then use it .DOM search is a costly operation
2.When you are using for loop,this would point to window object
check the following code snippet
$(document).ready(function(){
var someoneArray=$(".somename");
var someoneArrayLength=someoneArray.length;
var myValue=1;
for(var i=0;i<someoneArrayLength;i++){
var value=parseInt($(someoneArray[i]).text());
console.log(this)
if(myValue == value){
alert("here");
$(someoneArray[i]).text("changed");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="somename">1</li>
<li class="somename">2</li>
<li class="somename">3</li>
<li class="somename">1</li>
</ul>
Hope this helps

Adding/removing class dynamically

Hello I have a menu and I would like to remove the class active an add it to the element that I click....that was my idea but it is not working so well...
<div id="header2">
<div class="menu">
<ul>
<li id="menu_1" onclick="abrirPag('home.html')">Home</li>
<li id="menu_2" onclick="abrirPag('calendario_2014.html')">Calendário</li>
<li id="menu_3" onclick="abrirPag('classificacao_2014.html')">Classificação</li>
<li id="menu_4" onclick="abrirPag('equipes_2014.html')">Equipes</li>
<li id="menu_5" onclick="abrirPag('recordes.html')">Recordes</li>
<li id="menu_6" onclick="abrirPag('regulamento_2014.html')">Regulamento</li>
</ul>
</div>
</div>
Onload function to add the class active to the first item:
window.onload=function() {
var containermenu = document.getElementById("header2");
var navitemmenu = containermenu.querySelector(".menu ul li");
var identmenu = navitemmenu.id.split("_")[1];
navitemmenu.parentNode.setAttribute("data-current",identmenu);
navitemmenu.setAttribute("class","active");
Function to change the class:
function abrirPag(valor){
var currentmenu = this.parentNode.getAttribute("data-current");
document.getElementById("menu_" + currentmenu).removeAttribute("class");
var identmenu = this.id.split("_")[1];
this.setAttribute("class","tabActiveHeader");
this.parentNode.setAttribute("data-current",identmenu);
I get the following error when I click any of the elements: "Uncaught TypeError: Cannot call method 'getAttribute' of undefined "
Can someone help me?
You can use the dom classList to add remove classes
var element = document.getElementById("someId");
//Use add to add a class
element.classList.add("active");
//use remove to remove a class
element.classList.remove("active");
You will need a polyfill to use it on IE < 10 and some of the older versions of browsers.
To remove from all other menu and add to current do as cookie monster suggest and also pass the element to your function
function abrirPag(ele,valor){
var current = document.getElementsByClassName("tabActiveHeader");
if(current[0]){
current[0].classList.remove("tabActiveHeader");
}
ele.classList.add("tabActiveHeader");
}
The this value in an inline handler will be the window object instead of the element. You need to pass this to get it to the function.
<li id="menu_1" onclick="abrirPag(this, 'home.html')">Home</li>
Then reference it as the first element.
function abrirPag(elem, valor){
var currentmenu = elem.parentNode.getAttribute("data-current");
document.getElementById("menu_" + currentmenu).className = "";
var identmenu = elem.id.split("_")[1];
elem.className = "tabActiveHeader";
elem.parentNode.setAttribute("data-current",identmenu);
}
I also changed it to use the .className property instead of .get/setAttribute() for getting and setting the class.
Here it's a tip: use jQuery, you'll have a much easier life:
$("#header2 .menu li a").on("click", function(e) {
e.preventDefault();
var index = $("#header2 .menu li a").index(this);
$("#header2 .menu li a").removeClass("active").parent().parent().data("current", index);
$(this).addClass("active");
$(".content").text($(this).attr("href"));
});
Take a look at this Fiddle I've created!

Categories

Resources