How to replace all the text in the text in a loop? - javascript

Sorry for my english =)
I need to replace some of the elements on a page. Here is my code:
var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = $('body').html().replace(/text2/, 'text22');
var text3 = $('body').html().replace(/text3/, 'text33');
array = [text1, text2, text3];
for (var i = 0; i < array.length; i++) {
$('body').html(array[i])
};
But to replace only the first and third, if you remove the third element array, first and second is changed. Please tell me how to do it. Thank you!

var items = [
{ find: /text1/, replace: 'text11' },
{ find: /text2/, replace: 'text22' },
{ find: /text3/, replace: 'text33' }
];
var text = $('body').html();
for (var i = 0; i < items.length; i++)
{
var item = items[i];
text = text.replace(item.find, item.replace);
}
$('body').html(text);

That's because the original body html remains unchanged when the variables are evaluated. You would need to chain the replaces or use the previous variables for another replaces:
var text1 = $('body').html().replace(/text1/, 'text11');
var text2 = text1.replace(/text2/, 'text22');
var text3 = text2.replace(/text3/, 'text33');
And then you don't need any iterations..
$('body').html(text3);

Related

How to change innerHTML of each item in a list of webelements with nested classes

I am trying to make a javascript webextension that adds a couple numbers eg. "123" to the end of the inner text of a hyperlink text to each product on a shopping website, http://www.tomleemusic.ca
for example, if i go to this link, http://tomleemusic.ca/catalogsearch/result/?cat=0&q=piano
I want to add some numbers to the end of each product's name.
name of product and its nested hyperlink
so far, I have attempted the following code but it does not produce any results. Thanks for helping :)
var products= document.querySelector(".category-products, .products-
grid category-products-grid itemgrid itemgrid-adaptive itemgrid-3col
centered hover-effect equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
productslist[i].getElementsByClassName("product-name").innerHTML =
productslist[i].getElementsByClassName("product-name").innerHTML +
"1234";
}
Your query is wrong and you should use querySelectorAll instead of querySelector for fetching all elements matching the query.
Below is the code required as per given site:
var productsListLink = document.querySelectorAll(".products-grid .item .product-name a:not(.product-image)");
for (var i = 0; i < productsListLink.length; i++) {
var a = productsListLink[i];
var name = a.innerHTML || "";
name += "1234";
a.innerHTML = name;
a.setAttribute('title', name);
}
I guess I found what you needed.
var products = document.querySelector(".category-products .products-grid.category-products-grid.itemgrid.itemgrid-adaptive.itemgrid-3col.centered.hover-effect.equal-height");
var productslist = products.getElementsByClassName("item");
for (var i = 0; i < productslist.length; i++) {
var productName = productslist[i].getElementsByClassName("product-name")[0].firstChild;
productName.innerHTML = productName.innerHTML + "1234";
}

JS - combining array items together in one item

For example I want to collect some tags (lets say paragraph):
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length
I loop through (iterate):
for (var i = 0; i < tagsCollectionLength; i++)
{
//get an array:
var tagsCollectionArray = tagsCollection[i];
}
Now what to do to get all array items as ONE item:
so it won't looks like:
[paragraph1, paragraph2, paragraph3]
but like:
[paragraph1paragraph2paragraph3]
I did try join. concat. etc. without success probably I'm doing something wrong, any help is appreciated. Thanks.
you can keep a variable outside the for, append the strings inside for and when for finishes, push it inside an array.
Here's how to do that -
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length;
var tags = "", tagsCollectionArray = [];
for (var i = 0; i < tagsCollectionLength; i++)
{
tags = tags + tagsCollection[i];
}
tagsCollectionArray.push(tags);
Suppose you have this html
<div>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
</div>
Assuming the result you want is an Array of all the paragraphs's content ([paragraph1paragraph2paragraph3]), then you could do the following:
tagsCollection = document.getElementsByTagName('p');
var ar = [];
for(var i = 0; i < tagsCollection.length; i++ ) {
ar.push(tagsCollection[i].innerText)
}
console.log([ar.join('')]) // => ["abcde"]
See this fiddle
As I have already commented, you can use Array.join("").
JSFiddle.
(function() {
var data = [];
var str = [].map.call(document.getElementsByTagName('p'), function(item) {
return item.innerHTML;
}).join("");
data.push(str);
document.write("<pre>" + JSON.stringify(data) + "</pre>");
})()
<p>hello</p>
<p>workd</p>
<p>test</p>

Javascript. It is possible to add id on splitted word?? using word.split("")

var wtc = document.getElementById("sw").value;
var cw = wtc.split("").join(' ');
cw.toString();
var x=document.getElementById("demo");
x.innerHTML=cw;
I have this code. how can i add id to the splitted(am i right on my term??) word.. it is possible?
I want is to add id on each letter that is splited. I dont know the exact number of letter because it's depend on the user's inputted word.
for example. i have this word from split.
[W][O][R][M]
i want it to be something it this. or anything that have an id :)
<div id="DIVtext1">W</div>
<div id="DIVtext2">O</div>
<div id="DIVtext3">R</div>
<div id="DIVtext4">M</div>
Thanks!
do you mean something like:
var word = "WORM".split("");
var demoEle = document.getElementById("demo");
for(var w = 0, len = word.length; w < len; w++) {
var divEle = document.createElement("div");
divEle.id = "DIVtext"+(w+1);
divEle.onclick = (function(v) {
return function() { copyDiv( "DIVtext" + (v+1) ) };
})(w);
divEle.innerHTML = word[w];
demoEle.appendChild( divEle );
}
Demo: jsFiddle
Updated Demo:: jsFiddle Updated
You could use a loop (for(i=0;i<splittedArray;i++)) and jQuery to add div tags to the dom with the innerHtml being the word.
Basically, once you have it in your array you can put it wherever you want. I find that jQuery makes it easy; however, you could also do it through jscript alone.
This can be achieved pretty easily using jQuery.
var letters = $('#sw').val().split('');
$.each(letters, function(i, letter) {
$('<div />', {
id: 'DIVtext'+ i,
text: letter
}).appendTo('#demo');
});
JSFiddle
If jQuery isn't an option, here's what you can do with vanilla JS.
var letters = document.getElementById('sw').value.split(''),
demo = document.getElementById('demo');
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('div');
letter.innerHTML = letters[i];
letter.id = 'DIVtext'+ i;
demo.appendChild(letter);
}
JSFiddle

How to point elements childrens with JavaScript

I have little problem with element childrens.
Heres some code to explain my question:
function check(element){
// I want to get custom attribute from element children.
// Children elements are always radio buttons
var temp = element. ?? .attr('temp');
return temp;
}
// element variable is the whole div here
<div id = "test">
<table>
<tr>
<td> <input type="radio" temp="somethinghere"/></td>
</tr>
</table>
</div>
Hope someone has ideas or even better.. solution.
I think you want something like this:
function check(element) {
var ret = [];
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].type == 'radio') {
ret.push(element.childNodes[i].getAttribute('temp'));
}
}
return ret;
}
This will return an array containing all the temp attributes of the radio children of the element.
var temp = element.getAttribute('temp')
Or
var temp = element.temp = temp;
Or
var temp = element['temp'] = temp;
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: try:
var temp = '';
for (var i = 0; i < element.childNodes; i++)
temp += element.childNodes[i].getAttribute('temp');
return temp;
Is this what you're looking for?
To get an array of all the children of element :
element.childNodes;
To get an array of all input tags that are descendants of element :
element.getElementsByTagName("input")
Then loop through either of those arrays.
try this for the first child radio button
var temp = element.children(':radio:first').attr('temp');
of if you want all 'temp' attr from all child radio button do following:
var arrTemp = element.children(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();
UPDATE for table sample
var arrTemp = element.find(':radio').map(function(){
return $(this).attr('temp');
// or you can make it more detail like:
// return { ID: $(this).attr('id'), Temp: $(this).attr('temp') };
}).get();

Get each Attribute of element in loop function

I have a HTML DIV element:
<div class="obj" height="this is attr 1" rel="this is att2" width="this is att3"></div>
I've a new Variable: attArray:
var attArray = new Array();
I want to get step by step each att in div.obj into attArray. How do I do it?
attArray[0] = "this is attr1"
attArray[1] = "this is attr2"
attArray[2] = "this is attr3"
Each element already has an attributes-collection, you can access it like an array.
Simple:
$('.obj').each(function() {
var attArray = [];
for(var k = 0; k < this.attributes.length; k++) {
var attr = this.attributes[k];
if(attr.name != 'class')
attArray.push(attr.value);
}
//do something with attArray here...
});
Working example

Categories

Resources