I'm using an array to append to a base class name so I can iterate through different classes.
First bit works fine. Get a count on the array and as long as I exclude the last two lines of code I get all the desired class names in the console.
But once I add the last two lines the loop and try to add the constructed class name to get the different text values per class I get the following error:
Uncaught Error: Syntax error, unrecognized expression: '.moduleStatusDIS'
And it stops at the first iteration through the array. Code below.
function setModuleStatusColour() {
var array = ["DIS", "DDG", "CDX", "DKM", "DBV", "DBB", "DGK", "DAM", "LOG", "DUS", "DCL", "DRI"];
var arrayLength = array.length;
console.log(arrayLength);
for (x=0; x < arrayLength; x++){
var className = "'"+'.moduleStatus'+array[x]+"'";
console.log(className);
var statusValue = $(className).text();
console.log(statusValue);
}
}
I also tried to use eval() (although I know it's been deprecated, desperation got the better of me) see below. Same result as code above though.
function setModuleStatusColour() {
var array = ["DIS", "DDG", "CDX", "DKM", "DBV", "DBB", "DGK", "DAM", "LOG", "DUS", "DCL", "DRI"];
var arrayLength = array.length;
console.log(arrayLength);
for (x=0; x < arrayLength; x++){
var className = "'"+'.moduleStatus'+array[x]+"'";
console.log(className);
eval('var statusValue = $(className).text()');
console.log(statusValue);
}
}
Even tried to cast the var className into a String but didn work for me either.
If I write it out class by class and don't use an array to construct the names it works fine but I tried to keep the code short and make it easy to add. So it has become a matter of principle :)
Any help would be greatly appreciated!
This line:
var className = "'"+'.moduleStatus'+array[x]+"'";
should be simply
var className = ".moduleStatus" + array[x];
giving you a selector like
var statusValue = $(".moduleStatusDIS").text();
Selectors are just strings, there is no need to wrap it in single quotes.
It should be easy, just:
function setModuleStatusColour() {
var array = ["DIS", "DDG", "CDX", "DKM", "DBV", "DBB", "DGK", "DAM", "LOG", "DUS", "DCL", "DRI"];
var arrayLength = array.length;
console.log(arrayLength);
for (x=0; x < arrayLength; x++){
var statusValue = $('.moduleStatus'+array[x]).text();
console.log(statusValue);
}
Selectors are conformed by: $(-string-) where -string- should be the name of a class preceded by a dot (".className"), or the name of an element like $("div") (but this will select all div elements!), or the id of an element preceded by a # symbol like $("#sendButton")... The reason why .className and #sendButton are surrounded by quotation is that they are strings that refer to attributes given to elements like so:
<div class="className">...</div> --> $(".className")
<div id="sendButton">..<div> --> $("#sendButton")
<div>...</div> --> $("div")
Related
I want to get all elements from document which starts with ge-. Example <ge-survey></ge-survey> <ge-sombody></ge-sombody> <ge-...></ge-...>.
var elements = document.getElementsByTagName("*"); // <<-- now return all
also I tried :
var elements = document.querySelectorAll("^=ge-");
but get :
geadele.js:3 Uncaught SyntaxError: Failed to execute 'querySelectorAll' on 'Document': '^=ge-' is not a valid selector.
Also I tried:
var els = document.getElementsByTagName("^=ge-"); // return epty HTMLcollection
my html:
...
</head>
<body>
<ge-survey></ge-survey>
<ge-element></ge-element>
</body>
...
If you know all ge-elements, which you want to get, you can use document.getElementsByTagName('ge-somebody') and concatenate result.
var ge1Elements = Array.prototype.slice.call(document.getElementsByTagName('ge-1'));
var ge2Elements = Array.prototype.slice.call(document.getElementsByTagName('ge-2'));
...
var geElements = [].concat(ge1Elements, ge2Elements, ge3Elements);
In my opinion this approach in documents with a large number of elements is faster than regexp, but I didn't any benchmarks.
If you don't know all posible ge- elements, you can get it by filtering all elements:
var elements = document.getElementsByTagName("*");
var geElements = [];
for(var i = 0; i < elements.length; i++){
if(elements[i].tagName.indexOf('GE-') === 0){
geElements.push(elements[i]);
}
}
console.log(geElements);
You can use document.querySelector and use a 'starts with' type css selector:
Can I use a regular expression in querySelectorAll?
I'm trying to remove or replace characters in an element while using appendChild as follow:
var options = from.getElementsByTagName("option");
var to = document.getElementById("target");
to.appendChild(options[i].replace("(A)",""));
I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.
Thanks
I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.
to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));
Or better, in the loop append to a string, and create a single node at the end.
var txt = "":
for (var i = 0; i < options.length; ++i)
txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));
If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.
for (var i = 0; i < options.length; ++i) {
var clone = to.appendChild(options[i].cloneNode(true));
clone.text = clone.text.replace("(A)", "");
}
I have a div named box which contains three classes. I want to create a variable named relatedBoxes that stores the check boxes that share any of the same classes that box has.
I am splitting up the classes and storing them in the variable named splitClass.
I now just need the method to see whether :checkbox contains any of the classes saved within splitClass. I have tried by creating the variable relatedBoxes but this doesn't quite work.
The markup:
<div id="box" class="marker blue large">
The JavaScript:
var c = $('#box').attr('class');
var splitClass = c.split(' ');
var relatedBoxes = $(':checkbox').hasClass(splitClass);
Thanks a lot guys
hasClass expect a single class name, you're passing it an array right now. If you're trying to find all elements with marker, blue or large, something like:
var relatedBoxes = $( ':checkbox' ).filter( '.' + splitClass.join( ',.' ) );
You can use .filter() [docs] and iterate over the classes of the element:
var splitClass = $('#box').attr('class').split(' ');
var relatedBoxes = $('input[type="checkbox"]').filter(function() {
for(var i = 0, len = splitClass.length; i < len; i++) {
if($(this).hasClass(splitClass[i])) return true;
}
return false;
});
I need to get the text that is inside a element.
I can only grab the class of this element and NOT the ID.
<span class="fileName">test.png</span>
So I need a way to get test.png, but as you see I have only the class of the element and not the ID.
Just notice also that we may have more <span class="fileName"></span>, so it could look like this
<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>
In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.
Please help!
And also I am not a javascript expert!
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get();
The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.
You can test it here ยป
Update
Since you request the filenames to be a string separated by a comma, you can do it like this:
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get().join(',');
Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.
Use document.getElementsByClassName: http://jsfiddle.net/pCswS/.
var elems = document.getElementsByClassName("fileName");
var arr = [];
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr);
(Since you didn't tag the question with jQuery I assume you have to do it with plain JavaScript.)
$('span.fileName').each(function() {
var fileName = $(this).text();
doSomethingWithFileName(fileName);
});
Here the span.fileName selector returns all spans with class fileName then we iterate through, reading the text from each one. You may want to find a container element first and then only iterate inside that, e.g.
var $container = $('#myFileNames');
$container.find('span.fileName').each( ... );
Here's my take:
var spans = document.getElementsByClassName('fileName');
var values = [];
for(var i = 0; i < spans.length; i++) {
values.push(spans[i].innerHTML);
}
// Example of processing: alert the values
alert(values);
Use the following jQuery selector
$("span.fileName").html()
I am trying to first find a div using a regular expression (since its class name is somewhat dynamic).
Once found, I then need to place the div inside of a fieldset, so I end up having a final output of
<fieldset class="...">
<div class="the one I found">...</div>
</fieldset>
How can I do this in javascript?
Much thanks,
Steve
This is going to be difficult to do with regexes and ill-advised. For example, what if the div contains other divs? Finding the correct closing div tag is not something a regular expression can do because HTML is not a regular language.
On the other hand, this is a trivial one liner with jQuery:
$("div.someClass").wrap("<fieldset class='...'></fieldset>");
It can of course be done with vanilla Javascript DOM using something like:
var divs = document.getElementsByTagName("div");
for (var i=0; i<divs.length; i++) {
if (divs[i].className == "...") {
var fs = document.createElement("fieldset");
fs.className = "...";
var parent = divs[i].parentNode;
parent.insertBefore(fs, divs[i]);
fs.appendChild(divs[i]);
}
}
You of course need to fill in what class to put on the fieldset and change the test on the div to figure out if you need to manipulate it or not.
using jquery, you can try this:
var classes = $(document.body).html().match(/class="pattern"/g); // find classname matchin pattern
for(i in classes) {
var nodes = $('.'+classes[i].substr (7, str.length - 8));
nodes.wrap("<fieldset class='...' />");
}
window.onload = function() {
var params = {
has: "something"
};
// var fieldset = doc... get field the same as with div.
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (params.has.indexOf(divs[i].className) > 0) {
// fieldset.innerHTML = divs[i].innerHTML;
divs[i].innerHTML = "<fieldset class=''> + divs[i].innerHTML + "</fieldset>";
}
}
}
No need to use regular expression, indexof method is sufficient. And no need to use jquery. Javascript has good string and array functions - use them, but the DOM is a mess.