Change href and target of an anchor - javascript

I've wrote this so it changes the href of the anchor with the class name but I also would like it to change the target, how do I add this?
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0; i < change.length; i++) {
if (change[i].className.match('(^|\\s+)classnamegoeshere(\\s+|$)')) {
change[i].href = "/urlgoeshere";
break;
}
}
}

change[i].setAttribute('target', '_blank');

Try this
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0, j =change.length; i < j ; i++) {
if ((' ' + change[i].className + ' ').indexOf(' ' + "smeCls" + ' ') > -1) {
change[i].href = "http://www.google.com";
}
}
}

Related

Execute function on each element (with the same id)

I have this HTML code:
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
And i want to execute this JavaScript code on each one:
$(document).ready(function() {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#dadosalvaje');
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#dadosalvaje').attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
});
It just affects the first element and I can't find the way to modify both of them.
Is there any way to modify every single element with the same ID ?
First you need to make unique id
You do not need the "draconistone" class
Inside the $(document).ready(function() { and }); tags make the code a function with an id parameter like this:
function name(id) {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#' + id);
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#' + id).attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
}
Then execute the functions with the two different ids as parameters.
Maybe you can use $.each()
Like this
$('.draconistone').each(function() {
var zonaID = $(this).attr('class');
..
});
There is one for the same class
$( document).ready(function() {
$( ".draconistone" ).each(function( i ) {
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var texto = this.innerText.split(' ');
var resultado = texto.pop();
var zonaID = this.className;
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
this.innerHTML += '<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>';
this.id = 'salvajelisto';
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dadosalvaje1" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje2" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>

How do i convert a Jquery code to Pure javascript

I am using Bootstrap.
I am not able to figure out how to put this in pure javascript.This will open a div when we click on the accordion.
$(function() {
$("#panelTicketsList .list-group-item").on("click", function() {
$("#panelTicketsList .list-group-item").removeClass('selected');
$(this).addClass('selected');
if ($('#panelTicketsList').hasClass('col-md-12')) {
$('#panelTicketsList').removeClass('col-md-12').addClass('col-md-3');
$('.panelTicketDetail').removeClass('hide');
}
});
});
jsFiddle : https://jsfiddle.net/tqdc6yyL/
var listGroupItems = document.getElementsByClassName('list-group-item');
for (j = 0; j < listGroupItems.length; j++) {
listGroupItems[j].addEventListener("click", function () {
var elements = listGroupItems;
for (i = 0; i < elements.length; i++) {
if (elements[i].className.indexOf("col-md-12") > -1) {
elements[i].className = elements[i].className.replace("col-md-12", "col-md-3");
elements[i].className = elements[i].className.replace("hide", "");
}
}
this.className = this.className + " selected";
});
}
var list = document.getElementById('panelTicketsList');
var items = document.querySelectorAll("#panelTicketsList .list-group-item");
var detail = document.querySelectorAll(".panelTicketDetail");
items.forEach(function(btn){
btn.addEventListener("click", function(){
items.forEach(function(item){ item.classList.remove("selected"); });
this.classList.add("selected");
if(list.classList.contains('col-md-12')) {
list.classList.remove('col-md-12');
list.classList.add('col-md-3');
detail.classList.add("hide");
}
});
If you have to support older browsers like IE8 or IE9, you can't use JS features like forEach or classList. Instead you should use for loop and className.
//Save DOM query in variable for reuse
var panelTicketsList = document.getElementById('panelTicketsList');
var panelTicketsDetails = document.getElementsByClassName('panelTicketDetail');
var listGroupItems = panelTicketsList.getElementsByClassName('list-group-item');
//go through all of the listGroupItems and set click listener
for (var i = 0; i < listGroupItems.length - 1; i++) {
listGroupItems[i].addEventListener("click", function() {
//On click, go through all of listGroupItems and remove selected class
for (var j = 0; j < listGroupItems.length - 1; j++) {
listGroupItems[j].className = listGroupItems[j].className.replace('selected', '');
}
//Add selected class for clicked element
listGroupItems[i].className += 'selected';
//test if main element has class col-md-12
if (panelTicketsList.className.indexOf("col-md-12") > -1) {
//replace clas col-md-12 with col-md-3
panelTicketsList.className = panelTicketsList.className.replace('col-md-12', 'col-md-3');
//go through all of the panelTicketDetails and remove hide class
for (var k = 0; k < panelTicketsDetails.length - 1; k++) {
panelTicketsDetails[k].className = panelTicketsDetails[k].className.replace('hide', '');
}
}
});
}

Is this the correct way to use two loops in JavaScript

I am trying to check two things here, with two different for loops. One if a element has a attribute, that works! And the second loop should check if the alt tag is actually empty. I figured passing the first iterator value to the second would dispatch the second loop. But that doesn't work! Can someone help me out with this one?
function altChecker() {
var doc = document,
getStartedBtn = doc.getElementById('getStartedBtn');
EventUtility.addHandler(getStartedBtn, 'click', function() {
var all = doc.getElementsByTagName("IMG");
console.log('success!');
for (var i = 0, max = all.length; i < max; i++) {
if (all[i].hasAttribute('alt')) {
console.log('Yes, this has a ' + all[i].nodeName + ' tag!');
} else {
console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
}
}
for (var j = i, max2 = all; j < max2; j++) {
if(! $(all[j]).attr('alt')){
console.log('This is empty');
} else {
console.log('This aint');
}
};
});
}
I don't think 2 loops are required
function altChecker() {
var doc = document,
getStartedBtn = doc.getElementById('getStartedBtn');
EventUtility.addHandler(getStartedBtn, 'click', function() {
var all = doc.getElementsByTagName("IMG");
console.log('success!');
for (var i = 0; i < all.length; i++) {
if (all[i].hasAttribute('alt')) {
if (all[i].alt === '') {
console.log('this has a ' + all[i].nodeName + ' tag BUT it is empty!');
} else {
console.log('Yes, this has a ' + all[i].nodeName + ' tag and it is NOT empty!');
}
} else {
console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
}
}
});
}
You can do it in one loop. Check for the value of alt after checking if the attribute exists.
Note that alt is a standard property of the img tag but not div. In the example I used .getAttribute for the the non-standard property. If I used img tags then .getAttribute could be replaced with .alt since that's a standard property of the tag. see comments.
function altChecker() {
var out = [];
var doc = document;
var all = doc.getElementsByTagName("div");
for (var i = 0, max = all.length; i < max; i++) {
var id = all[i].id;
if (all[i].hasAttribute('alt')) {
out.push(id + ' has alt');
var value = all[i].getAttribute('alt');
if (value != "") {
out.push(id + ' alt="' + value + '"');
} else {
out.push(id + ' alt is empty');
}
} else {
out.push(id + ' does not have alt');
}
}
doc.getElementById('output').innerHTML = out.join("\n");
}
altChecker();
<div id='a' alt='foo'>-</div>
<div id='b' alt='bar'>-</div>
<div id='c' alt=''>-</div>
<div id='d'>-</div>
<pre id='output'></pre>
You're missing your .length property in the 2nd if:
max2 = all
Should be max2 = all.length
If you intended to loop though the all collection twice, you missed the length property on all in the second loop, and you need to start the j variable from 0.
for (var j = i, max2 = all; j < max2; j++) {
should be:
for (var j = 0, max2 = all.length; j < max2; j++) {
The two loops are completely independent and just iterate over the all collection; you write them in exactly the same way.
Mistakes like that are why I usually use functional idioms for looping:
$.each(all, function(idx, each){...});

Change script from start onclick to onload

I'm looking to change this script so that the animation starts once the page has loaded instead of when the div is clicked on.
Any suggestions on how I could do this would be much appreciated.
Here is the JS
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
});
function doScroll($ele) {
var top = parseInt($ele.css("top"));
if (top < -60) { //bit arbitrary!
var $lastEle = $ele.closest('.mholder').find(".last");
$lastEle.removeClass("last");
$ele.addClass("last");
var top = (parseInt($lastEle.css("top")) + $lastEle.height());
$ele.css("top", top);
}
$ele.animate({
top: (parseInt(top) - 60)
}, 80, 'linear', function() {
doScroll($(this))
});
}
Just move the code inside the .ready() event.
$(document).ready(function() {
$(".marqueeElement").last().addClass("last");
$(".mholder").each(function() {
var i = 0;
$(this).find(".marqueeElement").each(function() {
var $this = $(this);
$this.css("top", i);
i += $this.height();
});
});
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
Assuming '.mholder' is the selector for your div, just get rid of the click handler - i.e. change from:
$('.mholder').click(function() {
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
});
to
var countScrolls = $('.mholder .marqueeElement').length;
for (var i=0; i < countScrolls; i++) {
doScroll($('.mholder .marqueeElement:nth-child(' + i + ')'));
}
the most easiest way is to put at the end of the on ready function the following (after you bind the click event):
$('.mholder').click()

Adding a class to before and after links in a for statement using JavaScript?

I have a list of links in a UL. Can someone give me an example of how to detect what the index is of the link that was clicked, then add one class to all the links in LIs before the selected link and a different class to all the links in LIs after the selected link?
var ul = document.getElementById('your-ul'),
li = ul.getElementsByTagName('li');
var iterateLi = function(fn) {
for (var i = 0, length = li.length; i < length; i++) {
fn.call(li[i], i);
}
};
iterateLi(function(index) {
var thisIndex = index,
thisLi = this;
this.onclick = function(index) {
iterateLi(function(index) {
var classes = ['before', 'selected', 'after'],
addClass;
if (index < thisIndex) {
addClass = classes[0];
} else if (index == thisIndex) {
addClass = classes[1];
} else {
addClass = classes[2];
}
for (var i = 0, length = classes.length; i < length; i++) {
}
var className = this.className;
if (className) {
var regex = new RegExp('(?:' + classes.join('|') + ')', 'g');
className = className.replace(regex, '');
console.log(regex, className)
}
this.className = className + ' ' + addClass;
});
};
});
jsFiddle.

Categories