Change inner html not working [closed] - javascript

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.

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));
}

Why does .innerHTML edit the src attributes? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I'm making a chrome extension and trying to replace a certain word with another.
let allElements = document.querySelectorAll('*');
allElements.forEach(function (element) {
element.innerHTML = element.innerHTML.split(word).join("████");
}
The above code edits src and srcset attributes as well.
element.innerText and element.Textcontent removes all the CSS from the webpage.
Unfortunaly inner/outerHTML are changing all child elements too what causes them to be re-rendered by the browser (even if not changed). this also means you may "replace" some text multiple times if your selector received elements from all levels and the replacement text contains the original text too.
So the proper way is to change just the text-elements without touching the child-elements. This way you will not experience any of the mentioned problems:
let word = "yourword"
let allElements = document.querySelectorAll('*');
allElements.forEach(function (element) {
element.childNodes.forEach(function(el){
if (!el.nodeValue) return;
el.nodeValue = el.nodeValue.split(word).join("████");
});
});

Javascript set href for all elements in class [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 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>

Find a element by class from parent without querySelector or getElementsByClassName [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Following my code:
<div id="test">
<div>
<div class="find_me"></div>
</div>
</div>
I don't want to use querySelector or getElementsByClassName, how to create a while loop for each element in the id 'test' until you find the div with the class 'find_me'?
If I understood correctly
1) Get the children of test element. (here the variable is child)
var child = document.getElementById('test').children;
2) Iterate each of them, since it also needs to be iterated once again I'm iterating its children. (Not sure why JS has such a structure) (variable is children)
var children = child[i].children;
Final code:
var child = document.getElementById('test').children;
for (var i = 0; i < child.length; i++) {
var children = child[i].children;
for (var i = 0; i < children.length; i++) {
if (children[i].className == "find_me") {
alert("Yup, here I am");
}
}
}
I'm including a jsfiddle, so that you can check the console the reason for the ITERATIONS.
Hope you understood my logic.
(I agree with #MattBall)Try jQuery, this has clean methods like .filter(), .find() etc., You will love once you get your hands dirty on it.

JavaScript regex match id in innerHTML [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I managed to get all the text with .innerHTML, code should match all IDs which have pattern: sens[number] Is it possible to get the number? Is there some way around? And please no jQuery, thank you!
Preamble
Don't try to look for elements from the innerHTML string. Strings are hard to parse, and the DOM makes it really easy to search for elements with specific properties. With that said:
General Solution
// grab all elements on the page and setup an array to store matches
var els = document.getElementByTagName('*').
results = [];
// iterate over the elements
for (var i = 0; i < els.length; i++){
// see if the element has an id and, if so, if it matches
// the "sens[number]" pattern
if (els[i].id && /sens\[\d+\]/.test(els[i].id)){
// found a match, add it to results
results.push(els[i]);
}
}
Modern Solution
Of course you can also use querySelectorAll and look for [id^="sens["][id$="]"], but this can be problematic on older browsers (IE < 8).
var els = document.querySelectorAll('[id^="sens["][id$="]"]'),
results = [];
for (var i = 0; i < els.length; i++){
// all we've found are elements that start with "sens[" and
// end with a "]". We still need to verify there's a number
// between the brackets ([])
if (/sens\[\d+\]/.test(els[i].id)){
results.push(els[i]);
}
}
If you are simply trying to get the elements that have a similar id
var elements = document.querySelectorAll('[id^="sens[number]"]');
^= will match any id starting with sens[number]
if number is supposed to be dynamic
var elements = document.querySelectorAll('[id^=sens]');
grabs all that start with sens or you could use a variable with the selector to get a specific ones with a number
var number = 1;
var elements = document.querySelectorAll('[id^=sens"['+number+']"]');

Categories

Resources