Replace string of text javascript - javascript

Im trying to replace a string of text for another string of text here is my code plus js fiddle
HTML
<div class="label">Rating:</div>
<div class="data rating">****</div>
Javascript
var str=document.getElementsByClassName("data" ,"raiting").innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting").innerHTML=n;
Demo
http://jsfiddle.net/sgGQz/1/

document.getElementsByClassName() method returns, as its name suggests, a collection (HTMLCollection) of elements, not a single one -even if there's just a single element with the given classname(s) in DOM.
You need to go through each of them in order to make such a replacement. For example:
var elements = document.getElementsByClassName("data rating");
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].innerHTML = elements[i].innerHTML.replace(/\*/g, 'star');
}
JSFiddle.
Alternatively, if you know for sure that there should be only a single element, you can assign it directly:
var elementToAdjust = document.getElementsByClassName("data rating")[0];
// ...

If you only have one occurrence of the element this will work:
var str=document.getElementsByClassName("data rating")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data rating")[0].innerHTML=n;
If multiple data rating elements exist use:
var elems =document.getElementsByClassName("data rating");
for(var i = 0; i < elems.length; i++){
elems[i].innerHTML = elems[i].innerHTML.replace(/\*/g,"star");
}
Both method correct some flaws in the original code.
First, rating was misspelled in the argument passed to getElementsByClassName. Second, getElementsByClassName() uses class names delimited by spaces to select elements with multiple classes, instead of multiple arguments. Get elementsByClassName returns an array of elements which must be iterated through.
JS Fiddle: http://jsfiddle.net/sgGQz/5/

You need to check again for getElementsByClassName,It returns node-List, so you can do like this and You can loop through then after each element and set your value
var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML;
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;
Here is the example as you have only one occurance

Related

Finding index in array based on DIV text

I have a DIV which has text in it:
<div id="x">
divText
</div>
I have a "header row" like this:
var headerRow = ["wrong","wrongAgain","divText"];
I also have an array like this:
var theArray = [["blah","blah","0"]["notIt","blahblah","1"],["unrelated","dontLook","0"]];
I want to find the index in theArray (2) based on the text within the div:
var theDiv = x.innerHTML;
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv){ <--never works
if (headerRow[i] == x.innerHTML) { <---never works
if (headerRow[i] == "divText") { <--works (i = 2)
}
How can I find the index based on the innerHTML of a div / variable (first two cases above)? Thanks!
You are using innerHTML where as which returns content of HTML element including spaces and new lines.Instead use innerText or use methods trim method on either innerHTML or textContent.
In your case the comparision is not successful because the text that you are extracting using innerHTML contains spaces and newline.
Note:If element ID is valid identifier it can be used directly as
window.elementid or just elementid but it's best practice to use getElementByID
var x = document.getElementById('x')
var theDiv = x.innerHTML.trim();
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv) {
// your codes goes here
console.log('works')
}
}
or You can use
var theDiv = x.innerText
or
var theDiv = x.textContent.trim()
<div id="x">
divText
</div>
<script>
var headerRow = ["wrong","wrongAgain","divText"];
var theDiv = document.getElementById('x').innerHTML;
console.log(theDiv);
for (i=0; i < headerRow.length; i++){
if (headerRow[i] == theDiv.trim()){
console.log(headerRow.indexOf(headerRow[i]));
console.log(i);
}
}
</script>
Your if comparison doesn't work because of extra whitespace/new line in the div's innerHTML text. Thus you need to trim the string before comparing it with the contents of the header row array. Note that you can either use the indexOf method to get the index of the matching element, or you can just use the current value of i, which would also correspond to the index of that element. Hope this makes sense to you.
To get the text from div you should get element by id first
var theDiv = document.getElementById("x").innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
It will work with 1sth array, and the 2nd nested array can be flattened first
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

javascript parse text from <a href> links

Lets say I have
ThisTextChanges
ThisTextChanges
ThisTextChanges
ThisTextChanges
I want to iterate through these and get the "ThisTextChanges" which are some numbers that changes, most accurately timers.
How can i achieve that? jquery is fine.
They are inside a div with id "main_container".
I need to put the text in a var so the href is importanto to know which var i use for each one.
Lets break the task down into several steps:
Get a handle to all of our links (document.querySelectorAll)
learn how to get the current text of an a tag (childNode[0].nodeValue)
put it all together (Array.from, Array.map)
Get a handle to all of our links:
we will use document.querySelectorAll to get list of all nodes that match our selector. here I'm just going to use the selector a, but you probably have a class that specifies these links vs other links on the page:
var links = document.querySelectorAll('a');
Get the text of a link
This one is a bit more complicated. There are several ways to do this, but one of the more efficient ways is to loop through the child nodes (which will mostly be text nodes), and append the node.nodeValue for each one. We could probably get away with just using the nodeValue of the first child, but instead we'll build a function to loop through and append each.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
Put it all together
To put it all together we will use Array.map to turn each link in our list into the text inside it. This will leave us with an array of strings. However in order to be able to pass it to Array.map we will have to have an array, and document.querySelectorAll returns a NodeList instead. So to convert it over we will use Array.from to turn our NodeList into an array.
function getText(link){
var text = "";
for (var i = 0; i < link.childNodes.length; i++){
var n = link.childNodes[i];
if (n && n.nodeValue){
text += n.nodeValue;
}
}
return text;
}
var linkTexts = Array.from(document.querySelectorAll('a'))
.map(getText);
console.log(linkTexts);
this is text
this is some more text
You can just add condition in the a selector as follows:
var array = [];
$('#main_container a[href="/example2"]').each(function(){
array.push($(this).html());
});
console.log(array);
You can iterate and store them in an Array
var arr = [];
$("a").each(function(){
arr.push($(this).text());
console.log( arr );
});
you can achieve that in may ways. this example using for loop.
var main_container = document.getElementById("main_container");
var items = main_container.getElementsByTagName("a");
for (var i = 0; i < items.length; ++i) {
// do something.....
}
var array = [];
$('#main_container a').each(function(){
array.push($(this).html());
});
console.log(array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_container">
ThisTextChanges 1
ThisTextChanges 2
ThisTextChanges 3
ThisTextChanges 4
</div>
Please try:
$('#main_container > a[href]').each(function() {
var tes = $(this).attr('href').substring(1);
window[tes] = $(this).text();
});
123 will produce var named example1 with value 123, and so on.

Getting a string within a string Javascript

I have an html page with a few divs on it. Each div has one of these classes: tabCurrent, tabVisit, tabNext. I'm trying to search the string.className and get a substring that starts with "tab" but returns the full word, tabCurrent, etc.
I've tried various functions such as string.match(/tab\w/), string.exec(), string.includes(). A lot of the functions that find the string within a string, only return a Boolean..Or, you need to know the index and length already. Is there a good way to do this without using a while loop and starting at a known index and continuing until a white space to build the string?
EDIT: I've reworded my question
Say I have a string
var className = 'someClass tabCurrent tabVisit someOtherClass';
I want to get the classes that start with "tab". I'm trying to achieve this using string.match(). Is there a regex expression to pass in that would achieve this?
If there is only one tabSomething class you may use a match like this:
'someOtherClass tabVisit'.match(/\btab.+?\b/); //['tabVisit']
For multiple matches you have to enable the global g flag on the regex.
This will return "tabCurrent" for <div class="tabCurrent">:
div.className.match(/tab.+/g);
Here you go.
Collect all divs
Loop each div and get its className
Split className to array of classes
Match each class against regex that validates it starts with tab: /^tab/
If it matches insert to array
var divs = document.getElementsByTagName('div');
var classRegex = /^tab/;
var matchedClasses = [];
for (var i = 0; i< divs.length; i++) {
var currentDiv = divs[i];
var className = currentDiv.className;
var classNames = className.split(' ');
for (var curClass of classNames) {
if (curClass.match(classRegex)) {
matchedClasses.push(curClass);
}
}
}
console.log(matchedClasses)
<div class="tabCurrent"></div>
<div class="wrapper tabOther tab-three"></div>
<div class="different"></div>

JavaScript use for loop to create p tag with innerHTML content filled in

i am using a for loop to generate paragraph tags based on the length of my array. I want each of these p tags generated to have the same innerHTML. I can get the tags to generate with the class name but the innerHTML remains blank.
I have tried the following to no avail, not sure what I am doing wrong.
for (i = 0; i < numArray.length; i++) {
var line = document.createElement("p");
line.className = "line";
document.body.appendChild(line);
var b = document.getElementsByClassName("line");
b.innerHTML = "|";
}
You don't need to call getElementsByClassName you can change the innerHTML of line since you already have the reference to the DOM element.
for (i = 0; i < numArray.length; i++) {
var line = document.createElement("p");
line.className = "line";
line.innerHTML = "|";
document.body.appendChild(line);
}
And explaining why it didn't work, it's because getElementsByClassName returns a collecion of elements, you need to loop through them.
getElementsByClassName should return an array of elements, not a single element. You could try: getElementsByClassName('line')[i], if there is some reason you are doing that specifically.
Note: getElementsByClassName('line')[i] may not refer to the object you just created, unless there are no other "line"s on the page. It scans the document for all elements that have a class called line, which could be paragraphs or other element types.
For a better alternative, please refer to changes made below. This:
caches the numArray length into a variable, so you are not performing that operation at each loop iteration
sets the HTML and ClassName of the element you created before attaching it to the document; which has a number of performance benefits
does not unnecessarily do a DOM lookup for elements, which is expensive
uses the var keyword to avoid scoping conflicts for loop variables
JS Fiddle:
for ( var i=0, n=numArray.length; i < n; i++) {
var line = document.createElement("p");
line.className = "line";
line.innerHTML = '|';
document.body.appendChild(line);
}

find div in html with javascript and regex

I try to select html element with javascript without! jQuery...
for example my html is:
<div id="my1231">
</div>
and i want to select any first div with id started with my, and i try so:
var regex = /my(.*)/;
var templateCode = document.match(regex)
alert(templateCode);
but nothing happend, what i do wrong?
how to select div with regex, where first part of id is static, and second random?
How about document.querySelectorAll?
document.querySelectorAll("[id^='my']")
Just be aware of the >= IE8 support
http://caniuse.com/#search=querySelectorAll
If you really want to use regex to match against ids, you must first get a node list and then loop through it and check each id individually. You can then append each matching element to a new array:
var divs = document.getElementsByTagName('div');
var regex = /my(.*)/, matches = [];
for(i=0; i< divs.length; i++){
if(regex.test(divs[i].id)){
matches.push(divs[i]);
}
}
JSFiddle
Of course you can always mix both answers and use feature detection to determine which method to use:
var divs;
var matches = [];
var re = /^my\w+/;
if (document.querySelectorAll) {
matches = document.querySelectorAll("[id^='my']");
} else if (document.getElementsByTagName) {
divs = document.getElementsByTagName('div');
for(i=0, iLen=divs.length; i<iLen; i++){
if (re.test(divs[i].id)) {
matches.push(divs[i]);
}
}
}
HTH.

Categories

Resources