JavaScript regex match id in innerHTML [closed] - javascript

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+']"]');

Related

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.

Iterating through all the instances with name having a common string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Is there a way to access all the object instances starting with a common string.
Example: I have instances named button64, button223, button856471, button229846, etc. I have no control over how these instances are named. I want to push all these in an array.
I am not creating these objects, I just have to write a javascript which sits in this HTML page and collects all the object instances starting with the string 'button'.
The purpose is to reach out to a desired object out of these and change the visual element.
Also, the solution has to be compatible with IE8. Any ideas about how should I iterate?
If you can use jQuery, you could write:
var buttonsArray = [];
$("div").each(function() {
var id = $(this).attr("id");
if (id && id.indexOf("button") == 0) {
buttonsArray.push($(this));
}
});
You can use regular expressions to find any expression matching the pattern. Using the match method, every instance of the pattern is returned as an array.
var str = document.getElementById("sample");
var arr = string.match(/button[\d]*/g);
The regular expression on line two will match any result that has "button" and will stop once it encounters a character afterwards that is not a digit.

Increase performance for array manipulation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using as certain code in JavaScript where I have to append a huge amount of data such as 10000 objects at a time to an array, and in a click event I again empty that array and reload that array with 10000 objects. Here is my code snippet:
where "Nodes" is an array populated from user datasource.
var Index = 0;
var _array = new Array();
for (var i = 0; i < this.Nodes.length; i++) {
if(this.Nodes.PLeft>this.Nodes.Cleft){
var temp = {};
temp["PLeft"] = this.Nodes.PLeft;
temp["CLeft"] = this.Nodes.CLeft;
temp["PWidth"] = this.Nodes.PWidth;
temp["CWidth"] = this.NodesCWidth;
temp["PTop"] = this.Nodes.PTop;
temp["CTop"] = this.Nodes.CTop;
temp["Height"] = this.Nodes.Height;
_array[Index++] = temp;
}
}
This works fine with Firefox, but for IE and Chrome the performance is too bad -- sometimes the browser crashes. I have also used push() method for array, but I did not find much difference in the performance. Does anyone have any idea on how to improve performance of array manipulation?
A few issues here. First, your loop does not access the individual elements of this.Nodes. Because you keep referring to this.Nodes.PLeft (for example), you wind up with the same probably-undefined value. You must specify the index, this.Nodes[idx].PLeft.
This, of course, begs the question: why do you need to loop some array and turn it into... an array? Can't you just use this.Nodes directly instead of transferring it all into _array first?
Another thing: to reduce the weight of a loop, get the max length outside of the loops conditional statement. Doing it within the conditional causes that value to be looked up every time, by putting it into a variable the lookup only happens once.
You can eliminate the temp object and add the new array element directly. Likewise, you can eliminate the redundant counter and use the for... loop's counter.
var _array = [];
var maxlen = this.Nodes.length;
for (var idx = 0; idx < maxlen ; idx++) {
if(this.Nodes[idx].PLeft > this.Nodes[idx].Cleft){
// use idx for the array key IF you want it to match with this.Nodes indexes
// if you don't care, use _array.length
_array[_array.length] = {
'PLeft':this.Nodes[idx].PLeft,
'CLeft':this.Nodes[idx].CLeft,
'PWidth':this.Nodes[idx].PWidth,
'CWidth':this.Nodes[idx].CWidth,
'PTop':this.Nodes[idx].PTop,
'CTop':this.Nodes[idx].CTop,
'Height':this.Nodes[idx].Height
};
}
}

remove all elements in array with .remove() [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I have an array of numbers, let's say ["1", "3", "2"]
they correspond to values of the data-cardNumber attribute I've given to certain elements.
I want all elements with the data-cardNumber values in the array to be removed.
I tried doing this by iterating through the array and constructing a selector per each item in the array that calls .remove(), but that doesn't work.
I think the selector is too complex since it spans multiple strings.
How can I iterate through the array and .remove() all elements with the data-cardNumber attribute whose values are in the array?
Here is the code that I tried:
for(var i=0; i<swipedAwayCards.length; i++){
$('[data-cardNumber="'+swipedAwayCards[i]'"]').remove();
// i'm trying to construct a selector like [data-cardNumber="1"]
}
Looks like it's just a syntax error, which should have shown up in console:
$('[data-cardNumber="'+swipedAwayCards[i]+'"]')
(You missed the final + in your concatenation).
You could try the following:
$('[data-cardNumber="'+swipedAwayCards[i] + '"]').each(function() {
$(this).remove();
});
This should work rather than doing a for loop since jquery already has the capability to iterate over all matches of a selector.
You may need to do either of the the Following
var a = [1,2,3,4];
for(var i = 0 ; i< a.length; i++){
delete(a[i]); // This resets the value to undefined
}
which produces the following result
[undefined, undefined, undefined, undefined]
or
var a = [1,2,3,4];
var b;
for(var i = 0 ; i< a.length; i++){
b = a.pop();// This actually removes the Element from array and puts it in the variable b
}
Result: ** b = 1 At last as last element to be popped will be 1 and b = []**

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.

Categories

Resources