is it possible to amend the following html into the source linked at the bottom of this page? I have limited scripting access to the source page so I'm looking for a way to change the page using jquery or js.
Also the department id's will be completely random and there will be a different number of links relative to each group, therefore it will need to be dynamic. I've tried appending but I'm having trouble as inserting starting or closing tags only, so not sure how to go about this. Thanks in advance for any help offered.
Additions I need in the code are marked with **'s
Original source:
<ul class="menu">
<a id="group-car" href="#">Car</a>
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
<a id="group-bike" href="#">Bike</a>
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
</ul>
What I need to end up with:
<ul class="menu">
**<li>**
<a id="group-car" href="#">CAR</a>
**<ul class="acitem">**
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
**</ul>**
**</li>**
**<li>**
<a id="group-bike" href="#">BIKE</a>
**<ul class="acitem">**
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
**</ul>**
**</li>**
</ul>
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
jQuery(this).nextUntil("a").wrapAll("<ul></ul>");
});
jsfiddle
Does this need some explanation?
EDIT oops! I didn't see the classes on them:
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
var jUL = jQuery("<ul></ul>").addClass("acitem");
jQuery(this).nextUntil("a").wrapAll(jUL);
});
jsFiddle
What a beautiful challenge!!
Here you have. Tested in FF 3.6 and works!
function fixMarkup(){
var liFamilies = [];
var iFamily = 0;
$(".menu li").each(function(){
if($(this).prev().is("a"))
liFamilies[iFamily] = [this]; //Start a family
else
liFamilies[iFamily].push(this); //Append to family
if($(this).next().is("a")) iFamily++; //A new family begins
});
//console.log(liFamilies);
for(var i = 0; i< liFamilies.length; i++){
var family = liFamilies[i];
$(family).wrapAll('<ul class="acitem" />');
var ulNew = $(family[0]).parent()[0];
var aElem = $(ulNew).prev()[0];
$([aElem, ulNew]).wrapAll("<li/>");
}
}
$(document).ready(function(){
fixMarkup();
});
Related
I'm new to JS and for some reason I cannot for the life of me get a simple button to add a class to my links. I've tried a few different approaches that I've seen on here, and I get nothing. I'm embarrassed to say I've been at this for about 2 hours. I don't want to use jQuery because I want to learn JS, so if you could please provide the answer in raw JavaScript and explain your answer I would appreciate it. Thank you.
html:
<div class='col-9 text-right'>
<ul class='navlinks'>
<li>Home</li>
<li>Blog</li>
<li>About</li>
<li>Contact</li>
</ul>
<p class='cheesebrgr'>click</p>
</div>
JS:
var fries = function () {
var milkshake = document.getElementsByTagName(' li ');
for (i = 0; i < milkshake.length; i++); {
milkshake[i].classList.add('op1');
}
};
var napkin = document.getElementsByClassName('cheesebrgr');
napkin.addEventListener('click', fries);
**just read two more similar questions with no luck.
There are couple of problems in your code
document.getElementsByClassName() returns a list so you have to iterate to attach event listener
You are misplace ; in and terminated for loop
Code
for (i = 0; i < milkshake.length; i++); //<//misplace semi-colon end of for loop
var fries = function() {
var milkshake = document.getElementsByTagName('li');
for (var i = 0; i < milkshake.length; i++) {
milkshake[i].classList.add('op1');
}
};
var napkin = document.getElementsByClassName('cheesebrgr');
napkin[0].addEventListener('click', fries);
//If you single element with cheesebrgr class
//var napkin2 = document.querySelector('.cheesebrgr');
//napkin2.addEventListener('click', fries);
.op1 {
color: red;
}
<div class='col-9 text-right'>
<ul class='navlinks'>
<li>Home</li>
<li>Blog</li>
<li>About</li>
<li>Contact</li>
</ul>
<p class='cheesebrgr'>click</p>
</div>
I've run into a very strange problem.
I'm trying to create a search bar that has a dropdown button with many different search categories. Every link in the dropdown has the same id attribute each with a specific unique category attribute.
In my Javascript I used the querySelectorAll function to loop over all the elements and attach a click event listener which will execute my search function with one parameter (param):category attribute value.
However when the value is passed into the function I get [object MouseEvent] as the output. It's quite strange because the alert function that is called right before the function is called outputs the correct value. I'm not quite sure what is wrong
HTML Code:
<ul class="dropdown-menu dropdown-menu-right">
<li><a class="dropdown-item" id="search-users-btn" data-category="name" href="#">By First Name</a></li>
<li><a class="dropdown-item" id="search-users-btn" data-category="level" href="#">By Rank</a></li>
<li><a class="dropdown-item" id="search-users-btn" data-category="id" href="#">By ID</a></li>
</ul>
Javascript Code:
var searchBtn = document.querySelectorAll("[id=search-users-btn]");
for (var i = 0; i < searchBtn.length; i++) {
searchBtn[i].addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
alert(this.dataset.category); // This outputs the correct value.
searchQuery(this.dataset.category);//Everything goes wrong here
return false;
})
}
function searchQuery(param) {
var query = _("search-users-query-box");
if (!DN.value.empty(query.value)) {
window.location.href = encodeURI("/index/admin/search/param=" + param + "_" + query.value);
//Output looks like this: "/index/admin/search/param=[object%20MouseEvent]_somevaluehere"
} else {
query.style.borderColor = "red";
}
}
Try adjusting selector to className document.querySelectorAll(".search-users-btn") ; removing duplicate ids at search-users-btn , substituting adding search-users-btn as className at a elements
html
<ul class="dropdown-menu dropdown-menu-right">
<li><a class="dropdown-item search-users-btn" data-category="name" href="#">By First Name</a></li>
<li><a class="dropdown-item search-users-btn" data-category="level" href="#">By Rank</a></li>
<li><a class="dropdown-item search-users-btn" data-category="id" href="#">By ID</a></li>
</ul>
js
var searchBtn = document.querySelectorAll(".search-users-btn");
for (var i = 0; i < searchBtn.length; i++) {
searchBtn[i].addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
alert(e.target.dataset.category); // This outputs the correct value.
searchQuery(e.target.dataset.category); //Everything goes wrong here
})
}
I recently started learning javascript so i dont know much yet which is why i needed a some help and guidance.. , I want to make a list of images with links on a page which can be sorted in the order I want after clicking on "sort by author" or "sort by date" for example.. I tried to make something :
Javascript:
var wspeare = document.getElementsByClassName("willimshakespeare");
var jgreen = document.getElementsByClassName("johngreen");
function Sortbyauthor(author) {
this.author = author;
if (author === "williamshakespeare") {
for(i=0; i<wspeare.length; i++) {wspeare[i].style.display="block";}
for(i=0; i<jgreen.length; i++) {jgreen[i].style.display="none";}
};
else if (author === "johngreen") {
for(i=0; i<wspeare.length; i++) {wspeare[i].style.display="none";}
for(i=0; i<jgreen.length; i++) {jgreen[i].style.display="block";}
};
HTML:
<li class="williamshakespeare">
<img src="example"/>
</li>
<li class="johngreen">
<img src="example"/>
</li>
So when i did something like Sortbyauthor("johngreen") it worked but when the number of authors gets to 8-9 with 10-12 books the amount of code gets very repetitive and long plus the alignment of images gets weird.
So if anyone could guide me on how to make a sorting program that would be very helpful. After getting some practice with how DOM works I am planning to learn jQuery so if jQuery is needed for things like sorting then ill wait till I learn that.
Sorry if i posted this in the wrong forum or something its my first post...
Click run code snippet, then click sort
function doSort() {
//grab all the lis
var lis=document.getElementsByTagName('li');
//make an array to place each author into
var authors=[];
//go through each li
for (i=0;i<lis.length;i++) {
//put the author in the array
console.log(lis[i]);
authors.push(lis[i].getAttribute('class'));
}
//sort
authors.sort();
//get the ul
var ul=document.getElementById('authors');
for (i=0;i<authors.length;i++) {
console.log(authors[i]);
//grab each author in the array
li=document.getElementsByClassName(authors[i])[0];
//add it back, sorted
ul.appendChild(li);
}
}
<input type=button onclick=doSort(); value='click to sort' />
<ul id=authors>
<li class="williamshakespeare">william shakespeare
<img src="example"/>
</li>
<li class="johngreen">john green
<img src="example"/>
</li>
<li class="henrymiller">henry miller
<img src="example"/>
</li>
<li class="stephenking">stephen king
<img src="example"/>
</li>
<ul>
<div class="container-fluid">
<img class="pull-left" onclick="MarkPopup()" style="width:50px;height:50px" src="/assets/mark.jpg">
<ul class="nav pull-right">
<li>
<li>
Contact Club
</li>
<li>
<li class="dropdown">
</ul>
</div>
I want to change the href value "/ContactClub" to "somethingelse". How is this done please?
Two ways ;)
jQuery style:
// Select a with href attribute = /ContactClub
$('a[href="/ContactClub"]').prop('href', 'newhref...');
Pure-js solution (untested)
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (element[i].href === '/ContactClub') {
if (element.setAttribute !== 'function') {
element[i].href = 'newhref';
} else {
element[i].setAttribute('href', 'newhref');
}
}
}
I would add an id to the a tag:
<a id="contact_link" href="/ContactClub">Contact Club</a>
And then do either,
$('#contact_link').attr('href', 'new url');
or,
document.getElementById('contact_link').href = 'new url';
Note: You can also use the jQuery prop method in the same fashion as attr above. This is somewhat a matter of preference. As href is principally thought of as an attribute (with a corresponding, but not dynamic or disconnected js property), I would suggest using attr. Other attributes like value will depend on what you're trying to retrieve. Do a bit of research on the differences.
You can use either prop() or attr():
$('a[href="/ContactClub"]').attr('href', 'New Href here');
or:
$('a[href="/ContactClub"]').prop('href', 'New Href here');
Fiddle Demo
try
$("li a").attr("href","new value");
I am trying to create an array with different hrefs to then attach to 5 separate elements.
This is my code:
var link = new Array('link1', 'link2', 'link3', 'link4', 'link5');
$(document.createElement("li"))
.attr('class',options.numericId + (i+1))
.html('<a rel='+ i +' href=\"page.php# + 'link'\">'+ '</a>')
.appendTo($("."+ options.numericId))
As you can see I am trying to append these items from the array to the end of my page so each link will take the user to a different section of the page. But i have not been able to do this. Is there a way to to create elements with different links?
I am new to javascript so I am sorry if this doesn't make a whole lot of sense. If anyone is confused by what i am asking here I can try to clarify if I get some feedback.
The code I would Like output is:
<ul class="controls">
<li class="controls1"></li>
<li class="controls2"></li>
<li class="controls3"></li>
<li class="controls4"></li>
<li class="controls5"></li>
</ul>
Which is similar to what I am getting, however when I apply the fix that andres descalzo has supplied, my list elements are each repeating themselves 5 times.
Any solutions would be greatly appreciated.
Thanks,
jason
I'm not sure exactly what you want, as there is some undefined values and syntax errors in your code, but here is an example on how to create elements from an array and add to an existing ul element:
$(function(){
$.each(['link1', 'link2', 'link3', 'link4', 'link5'], function(i, link){
$('<li/>')
.append(
$('<a/>')
.attr({ 'class': 'c' + i, ref: i, href: 'page.php#' + link })
.text(link)
).appendTo('ul');
});
});
With the existing ul element, it produces:
<ul>
<li><a class="c0" ref="0" href="page.php#link1">link1</a></li>
<li><a class="c1" ref="1" href="page.php#link2">link2</a></li>
<li><a class="c2" ref="2" href="page.php#link3">link3</a></li>
<li><a class="c3" ref="3" href="page.php#link4">link4</a></li>
<li><a class="c4" ref="4" href="page.php#link5">link5</a></li>
</ul>
(In place of the array literal [...] you could of course use an array variable.)
something like this?:
*Edit II * for comment
var link = ['strategy', 'branding', 'marketing', 'media', 'management'],
refNumericId = $("."+ numericId);
$(link).each(function(i, el){
$("<li></li>")
.attr("id", numericId + "_" + (i+1))
.attr("class", numericId + (i+1))
.html("")
.appendTo(refNumericId);
});
I saw your code in the file 'easySlider1.7.js' and you're including in 'for' of the line 123 the code 'var link = [' strategy,''which should go after this 'for'