Javascript set href for all elements in class [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a list of (at least 4) < a > tags with the class 'remove-typefilter'
They do not have a 'href' ., but I want to give them all one when the users clicks a button.
This is the JS function I've written to achieve this:
function BuildButtons(urlparams) {
elements = document.getElementsByClassName('remove-typefilter')
for (let element in elements) {
element.href = 'www.newlink.com' + urlparams
element.style = 'color: red;'
}
}
Yet when I run this function it does not change the attributs. The A tags get no link and the styling goes not change.
Does anyone know what I am doing wrong?

Two issues:
Syntax error in the function definition: url-params is invalid. Use urlParams.
for ... in loops iterate the keys of the iterated object, not the values. Use for ... of instead
Also:
Do not define elements as a global variable. Use const.
Better add a protocol in your URL, like http://
Although assigning a string to style works, it is more efficient to assign directly to the relevant style property
Corrected code:
function BuildButtons(urlParams) {
const elements = document.getElementsByClassName('remove-typefilter');
for (const element of elements) {
element.href = 'http://www.newlink.com' + urlParams;
element.style.color = 'red';
}
}

you can set the href attribute by using the
Element.setAttribute(*name*,*value*);

for loops return the index not the actual element.
for (let element in elements) {
should be
for (let i in elements) {
let element = elements[i];
or
elements.forEach(function(element) {

Why not use querySelectorAll() and forEach()
function BuildButtons(urlparams) {
var elements = document.querySelectorAll('.remove-typefilter');
elements.forEach(function(element){
element.href = 'www.newlink.com' + urlparams
element.style = 'color: red;'
});
};
BuildButtons('#xxx'); // invoke call the function how ever you like.
<a class="remove-typefilter">one</a>
<a class="remove-typefilter">two</a>
<a class="remove-typefilter">three</a>

Related

Why cant I add same element to the web page again and again? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I am trying to add a <p> element 10 times in the <body>.. This is my code
body = document.getElementsByTagName("body")
text = document.createElement("p")
text.innerText = "I am batman"
let batman = 10;
for (i=0; i<batman; i++){
body[0].appendChild(text)
}
But the result is that I get only 1 <p> on the web page.. But when I create the element inside the for loop it works properly..
Why is this happening? Why was I not able to add same element to the page over and over again.
You'll need to create a new element within your loop each time it iterates because .appendChild() will only do exactly that, append the designated element as a child of the element it's called on. It doesn't create new elements, so using it with an existing element will just move it.
let batman = 10;
for (i=0; i<batman; i++){
// Each time you loop, create a new element
let p = document.createElement("p");
p.textContent = "I am sure";
document.body.appendChild(p);
}
You're creating 1 element and try to append that 10 times. Every iteration overwrites the previous. Either create a new HTMLParagraphElement every iteration, or use Node.cloneNode.
Here's a snippet using the latter.
// create a HTMLParagraphElement (in memory)
const p = Object.assign(document.createElement(`p`), {textContent: `I am batman`});
// append it 10 times using Node.cloneNode
// (deep, so textContent is cloned too)
for (let i = 0; i < 10; i += 1) {
document.body.appendChild(p.cloneNode(true));
}

Is there a better way targeting the last element child of previous sibling [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 12 months ago.
Improve this question
I mean the code does work, but at some point, it seems a bit weird to me, so I was wondering if someone does know a better way of targeting the last element child of the previous element sibling.
Basically, I have a slider which value I want to show with the span of its previous sibling, example:
<div class="xOffsetBox">
<label for="xOffset" class="xOffsetText">xOffset <span>0 px</span></label>
<input type="range" name="xOffset" id="xOffsetRange1" min="-100" max="100" value="0">
</div>
And, within a js function, I get the value of the range input.
function getRangeValue () {
for (let i = 0; i < Shadows.length; i++) {
let xOffset = document.getElementById(Shadows[i].xOffsetValue).value;
let xOffsetSpan = document.getElementById(Shadows[i].xOffsetValue).previousElementSibling.lastElementChild;
xOffsetSpan.textContent = xOffset + " px";
};
};
I'd probably use data-attributes they are quite useful. They don't pollute your css-class-attribute and it is not unique like id. Also, it is fairly easy to scale up.
There is not much you can do here with your query, since you try to work with a sibling.
The question is also: What are you trying to achieve here? What is "better" in your own words? Is it the lines of code, you want to reduce, reduce the complexity, or to find an alternative way? You could use an id, a class, or even a data-attribute on that sibling and just access it with document.querySelector or for id-lookup: document.getElementById. It really depends on what you try to accomplish.
You could, maybe, optimize it like this:
for (let i = 0; i < Shadows.length; i++) {
const el = document.getElementById(Shadows[i].xOffsetValue);
const xOffset = el.value;
const xOffsetSpan = el.previousElementSibling.lastElementChild;
xOffsetSpan.textContent = xOffset + " px";
};
This way you don't have to travel the DOM twice to find the element. You can also use const instead of let, if you don't want to modify these values.
Maybe even use a for-of iterator instead, if you like.

add a variable in href using javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am new in javascript i want to add a javascript variable in
i use some javascript like this but it not working
HTML
<ul id="direction"></ul>`
JS
var abc = 'link/';
var cba = 'hello';
document.getElementById('directions').innerHTML = 'Link';`
This code should work, make sure the html id matches the getElementById and use the right quotes as mentioned before.
You want to add a href to a list but you should add a li first, in my example I use a div tag.
var name = 'google';
var ext = '.com';
document.getElementById('direction').innerHTML = 'Link';
A better way to do this would be by using backticks `` < these like so:
var name = 'google';
var ext = '.com';
var link = 'Link';
document.getElementById('direction').innerHTML = `${link}`;
Your code, fixed ID, and quotes:
document.getElementById("direction").innerHTML='Link'
Or maybe better:
var node=document.createElement("A")
node.setAttribute("href","https://"+var1+var2)
document.getElementById("direction").appendChild(node)
I hope that this will help you!
I'd recommend avoiding using innerHTML in most cases! The following accomplishes what you want programmatically without needing to generate HTML strings:
window.onload = () => {
let abc = 'link/';
let cba = 'hello';
let container = document.getElementById('direction');
let link = container.appendChild(document.createElement('a'));
link.setAttribute('href', `https://${abc}${cba}`);
link.appendChild(document.createTextNode('Link'));
};
<ul id="direction"></ul>

JSON element pushing into array in Javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am looking to access a HTML element's data (a JSON record) and push it into an array in JavaScript.
The HTML is:
<td class="card-holder" data-card="{"id":0,"type":"Wildcard","image":"wildcard.png","strength":0,"type_image":"wildcard.png","region_owned_adder":0}">
<img id="card-image-0" src="/img/wildcard.png" class="card-exchange">
<input class="cards-checkbox" type="checkbox" id="card-0" name="cards_to_exchange[]" value="id=" 0""="">
<label for="cards_to_exchange"></label>
</td>
I have a number of these on my page. I read each in a loop and select some to push into an array like this:
var cards = [];
$('.card-exchange').each(function() {
if ($(this).find('input[name="cards_to_exchange[]"]').is(':checked')) {
var parseCard = JSON.parse(thisElement.data('card'));
cards.push(parseCard);
}
});
But this is showing me [] after the loop:
console.log(cards);
This shows the data OK:
console.log(thisElement.data('card'));
How do I read the string and push it into array as object? Thanks.
You're using .find() on an <img>, which has no descendants.
Use .next() instead to get its <input> sibling.
Also, you can use .filter() and then .map() to clean it up a little.
var cards = $('.card-exchange').filter(function() {
return $(this).next().is(':checked');
}).map(function() {
return JSON.parse(thisElement.data('card'));
}).toArray();
Though I'm not sure what thisElement is referring to.
You could even shorten it a little more.
var cards = $('.card-exchange + input:checked')
.prev()
.map(function() {
return JSON.parse(thisElement.data('card'));
});

Change inner html not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am having a problem trying to change some innerHtml with this piece of code bellow:
var element = document.getElementByClass("productitemcell > a");
element.innerHTML = "Remover";
It is suposed to change the innerHTML from a link that says"Remove" to "Remover" and its not working.
Here's the page of it: http://ooleiro.businesscatalyst.com/OrderRetrievev2.aspx
You have to buy some products to access this shopping cart page.
I think you meant document.getElementsByClassName()
This method will return a HTMLCollection object. You can grab the first element like so:
var elements = document.getElementsByClassName('class');
var firstElement = elements[0];
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
The method is called getElementsByClassName (plural) and returns a collection of HTML elements. For which one of those do you want to change the HTML? For the first one?
Additionally, you cannot use a CSS selector like that in standard DOM methods
EDIT: Obviously you want to change all occurrences of a elements inside all occurrences of .productitemcell:
var pics = document.getElementsByClassName("productitemcell");
for(i=0; i<pics.length; i++) {
// loop over all elements with that class
var anchors = pics[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
Had to change the class to
var removerprod = document.getElementsByClassName("remover");
for(i=0; i<removerprod.length; i++) {
// loop over all elements with that class
var anchors = removerprod[i].getElementsByTagName("a");
for(j=0; j<anchors.length; j++) {
// loop over all anchor elements within the current class element
anchors[j].innerHTML = 'Remover';
}
}
so it doesnt change the product name as well. the only problem remaining is that it is retrieving with ajax and everytime it refreshes it changes again to "Remove"Thank's you devnul69, i realy learned a lot today about js.

Categories

Resources