How to remove child (html div) from parentnode with for loop - javascript

So im trying to remove HTML div's from it's parent div.
I have a div which contains the div that need to be removed, selectedDivs.
However my current function refuses to remove more then 1 item from it's parent div...
Here's what i tried:
Console output: http://pastebin.com/KCeKv1pG
var selectedDivs = new Array();
canvas.innerHTML += "<div id="+currDev+" class='DRAGGABLE' onClick='addBorder(this)>" + "<img src='/devices/" + device + ".gif'></img></div>";
function addBorder(e) {
if (ctrlBeingpressed == true) {
selectedDivs.push(e);
e.style.border = "2px dotted black";
}
}
function deleteSelected() {
console.log(selectedDivs);
var len = selectedDivs.length;
for (var i = 0, len; i < len; i++){
console.log("before html remove: " + selectedDivs.length);
var node = selectedDivs[i];
node.parentNode.removeChild(node);
console.log("after html remove: " + selectedDivs.length);
for (var i in racks)
{
console.log(i);
if(node.id == racks[i].refdev)
{
console.log("Found in rack");
for (z = 1; z < racks[i].punkt.length; z++)
{
if(racks[i].punkt[z] != undefined)
{
if(racks[i].punkt[z].y.indexOf("S") > -1) //If it's an already defined point at an S card
{
//Clearing the TD
$("#sTab tr:eq("+(cardsS.indexOf(racks[i].punkt[z].y)+1)+") td:eq("+(racks[i].punkt[z].x-1)+")").html(" ");
$("#sTab tr:eq("+(cardsS.indexOf(racks[i].punkt[z].y)+1)+") td:eq("+(racks[i].punkt[z].x-1)+")").css("background-color","#E6E6E6");
}
else // Then it must be a P or V card
{
$("#pvTab tr:eq("+(cardsPV.indexOf(racks[i].punkt[z].y)+1)+") td:eq("+(racks[i].punkt[z].x-1)+")").html(" ");
$("#pvTab tr:eq("+(cardsPV.indexOf(racks[i].punkt[z].y)+1)+") td:eq("+(racks[i].punkt[z].x-1)+")").css("background-color","#E6E6E6");
}
}
}
console.log("Found in rack, breaking this loop");
delete racks[i];
break;
}
}
}

As discussed in the comments, there's a problem with resetting the value of the i variable within the nested loop. I took the liberty of editing the code to the way I would write it. I jQueried up some things since you're already using it anyway. (This code assumes you can target IE 9 or later and thus use Array.prototype.forEach and also that racks is an array, which seemed to be the case from the original.)
var selectedDivs = [];
$(canvas).append("<div id="+currDev+" class='DRAGGABLE' onClick='markSelected(this)'><img src='/devices/" + device + ".gif'></img></div>");
function markSelected(div) {
if (ctrlBeingpressed == true) {
selectedDivs.push(div);
$(div).css("border", "2px dotted black");
}
}
function deleteSelected() {
var i, z, deletedDivIDs = [];
console.log(selectedDivs);
selectedDivs.forEach(function(selectedDiv, index, selectedDivs) {
console.log("Removing", selectedDiv, "at index", index);
divIDs.push(selectedDiv.id);
selectedDiv.parentNode.removeChild(selectedDiv);
});
racks.forEach(function(rack, index, racks) {
console.log(i);
if(deletedDivIDs.indexOf(rack.refdev) !== -1) {
console.log("Found in rack");
for (z = 1; z < rack.punkt.length; z++) {
if(rack.punkt[z] !== undefined) {
if(rack.punkt[z].y.indexOf("S") > -1) {//If it's an already defined point at an S card
//Clearing the TD
$("#sTab tr:eq("+(cardsS.indexOf(rack.punkt[z].y)+1)+") td:eq("+(rack.punkt[z].x-1)+")").css("background-color","#E6E6E6").empty();
}
else { // Then it must be a P or V card
$("#pvTab tr:eq("+(cardsPV.indexOf(rack.punkt[z].y)+1)+") td:eq("+(rack.punkt[z].x-1)+")").css("background-color","#E6E6E6").empty();
}
}
}
racks[rack] = undefined;
}
});
}
I didn't have a chance to test this in real code since we still don't know what racks looks like, but hopefully this gets you further down the road.

you have created nested for loops with the same var i=0, It could be your problem.
And the other point I like to point out is, if racks is an array you'd better not use for(var i in racks) because it would scan all other prototype attributes in your Array.prototype, which depends on what libraries you have used in your page. and If racks is not an array, it would scan all other properties in your Object.prototype, what I mean is, if it is just a iteration using for(var i in racks) is not safe, because adding a new Javascript library could mess with your code.

Related

Dynamically load images, break loop on error

I asked this previously but didn't get an answer that applied to my project. I am trying to load images to a table dynamically without having to use server side code. It works, but I want to be able to have an infinite loop that breaks when a picture fails to load, rather than hard code the number of rows I need. That way I won't ever have to update the code, I'll just be able to add pictures to a folder if I want to expand the table.
Right now the "onerror" attribute hides the failed image, but I also want to break out of the outer loop (loop1).
function headCatalogLoader() {
var table = document.getElementById("catalog");
var meshNum = 0;
var uniqueID = 0;
loop1:
for (var i = 0; i <= 50; i++) { // i made it 50 instead of infinite for now
var row = table.insertRow(i);
loop2:
for (var k = 0; k <= 2; k++) { // 2 is because 3 columns
var skinTone = "none";
var cell = row.insertCell(k);
if (k == 0) {
skinTone = "lgt";
}
else if (k == 1) {
skinTone = "med";
}
else if (k == 2) {
skinTone = "drk";
}
cell.innerHTML = "<img src=\"headimgs/head" + skinTone + meshNum + ".png\" id=\"head" + uniqueID + skinTone + "\" onclick=\"previewIt(this)\" onerror=\"$(this).hide();\" />";
uniqueID++;
}
meshNum++;
}
var tbody = $("table tbody");
tbody.html($("tr",tbody).get().reverse());
}
Breaking from within the attribute is out of the loop's scope and doesn't work. Also using
$('img').on("error", function () {
break loop1;
});
inside loop2 doesn't do anything. Someone suggested I use a recursive method and rewrite my function, but that won't work for me since I'm dynamically creating a table and using image names that correspond to the loop. Any help or suggestions would be wonderful!
I'm thinking you could use an XMLHttpRequest to check the response for that URL before trying to put it onto the page. If status is not 404 then insert image else break loop1. Something like this might work:
function headCatalogLoader() {
var table = document.getElementById("catalog");
var meshNum = 0;
var uniqueID = 0;
loop1:
for (var i = 0; i <= 50; i++) { // i made it 50 instead of infinite for now
var row = table.insertRow(i);
loop2:
for (var k = 0; k <= 2; k++) { // 2 is because 3 columns
var skinTone = "none";
var cell = row.insertCell(k);
if (k == 0) {
skinTone = "lgt";
} else if (k == 1) {
skinTone = "med";
} else if (k == 2) {
skinTone = "drk";
}
// note: you'll need to use an absolute path for imageUrl
var imageUrl = "http://example.co.uk/example/headimgs/head" + skinTone + meshNum + ".png";
var xhttp = new XMLHttpRequest();
xhttp.open('HEAD', imageUrl, false);
xhttp.send();
if (xhttp.status !== 404) {
cell.innerHTML = "<img src=" + imageUrl + " id=\"head" + uniqueID + skinTone + "\" onclick=\"previewIt(this)\" onerror=\"$(this).hide();\" />";
uniqueID++;
} else {
break loop1;
}
}
meshNum++;
}
var tbody = $("table tbody");
tbody.html($("tr", tbody).get().reverse());
}
Note: you'll need to use an absolute path for the XMLHttpRequest. I've just used example.co.uk/example because I don't know your URL.
I'm guessing you're only expecting it to error if the image is not found, because that would indicate that you've reached the last image in your folder, which is why I checked !== 404, if you want to break in the case of any error (such as 500 internal server error), it might be best to change if (xhttp.status !== 404) to if (xhttp.status === 200).

Set the scroll position to search string in Xamarin.Ios

I am working on a xamarin.ios application to show the content in a text file into webview. I could able to display the content.
Now I need to add search feature, so that the selected string needs to highlighted and SCROLL need to position in to the search text. I am using below Javascript to highlight the searched text and highlighting is working as expected.
string startSearch = "MyApp_HighlightAllOccurencesOfString('" + searchStr + "')";
this.webView.EvaluateJavascript (startSearch);
How can I move the scroll position to the searched string using this webview?
Thanks in advance
Roshil K
You can use the code snippet to reset the scroll position of the WebView, like this:
webView.ScrollView.ContentOffset = new CGPoint(0,50);
But you have to know the (x,y) point of the related string. I am not familiar with Javascript, maybe it can be returned by your JS code.
Also, I found a solution via JS which maybe help you here:https://stackoverflow.com/a/38317775/5474400.
I got is solved by adding the below javascript to my existing "MyApp_HighlightAllOccurencesOfString" javascript.
var desiredHeight = span.offsetTop - 140;
window.scrollTo(0,desiredHeight);
My Complete Javascript is below.
this.webView.EvaluateJavascript ("// We're using a global variable to store the
number of occurrences
var MyApp_SearchResultCount = 0;
// helper function, recursively searches in elements and their child nodes
function MyApp_HighlightAllOccurencesOfStringForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
var span = document.createElement(\"span\");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute(\"class\",\"MyAppHighlight\");
span.style.backgroundColor=\"yellow\";
span.style.color=\"black\";
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
var desiredHeight = span.offsetTop - 140;
window.scrollTo(0,desiredHeight); MyApp_SearchResultCount++;\t// update the counter
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != \"none\" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}
// the main entry point to start the search
function MyApp_HighlightAllOccurencesOfString(keyword) {
MyApp_RemoveAllHighlights();
MyApp_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
}
// helper function, recursively removes the highlights in elements and their childs
function MyApp_RemoveAllHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute(\"class\") == \"MyAppHighlight\") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (MyApp_RemoveAllHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
function MyApp_RemoveAllHighlights() {
MyApp_SearchResultCount = 0;
MyApp_RemoveAllHighlightsForElement(document.body);
}");

Get CSS class definition from chrome developer tools console

I would like to programatically retrieve a set of CSS class definitions from chrome developer tools. In effect similar to what is displayed in styles tab in the right hand side. The input needs to be a class name and the output should be all the styles defined in it.
I'm aware of getComputedStyle DOM method, but this doesn't separate into separate classes which I need.
This approach worked for me (stackoverflow.com/a/27527462/1023562):
/**
* Gets styles by a classname
*
* #notice The className must be 1:1 the same as in the CSS
* #param string className_
*/
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
var ret;
if(classes[x].cssText){
ret = classes[x].cssText;
} else {
ret = classes[x].style.cssText;
}
if(ret.indexOf(classes[x].selectorText) == -1){
ret = classes[x].selectorText + "{" + ret + "}";
}
return ret;
}
}
}
}
It lets you invoke the javascript code in Chrome console like this:
console.log(getStyle('#heder_logo a'));
and get results like this:
> #heder_logo a { width: 200px; height: 114px; display: block; }.
I did have issues with some CSS files which were not on the same domain (they were pulled from CDN), but there are variety of proposals in that thread, so some should work for you.
Have adapted Ivan's answer in order to get a more complete result. This method will also return styles where the class is part for the selector
//Get all styles where the provided class is involved
//Input parameters should be css selector such as .myClass or #m
//returned as an array of tuples {selectorText:"", styleDefinition:""}
function getStyleWithCSSSelector(cssSelector) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
var arStylesWithCSSSelector = [];
//in order to not find class which has the current name as prefix
var arValidCharsAfterCssSelector = [" ", ".", ",", "#",">","+",":","["];
//loop through all the stylessheets in the bor
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
//check for any reference to the class in the selector string
if(typeof classes[x].selectorText != "undefined"){
var matchClass = false;
if(classes[x].selectorText === cssSelector){//exact match
matchClass=true;
}else {//check for it as part of the selector string
//TODO: Optimize with regexp
for (var j=0;j<arValidCharsAfterCssSelector.length; j++){
var cssSelectorWithNextChar = cssSelector+ arValidCharsAfterCssSelector[j];
if(classes[x].selectorText.indexOf(cssSelectorWithNextChar)!=-1){
matchClass=true;
//break out of for-loop
break;
}
}
}
if(matchClass === true){
//console.log("Found "+ cssSelectorWithNextChar + " in css class definition " + classes[x].selectorText);
var styleDefinition;
if(classes[x].cssText){
styleDefinition = classes[x].cssText;
} else {
styleDefinition = classes[x].style.cssText;
}
if(styleDefinition.indexOf(classes[x].selectorText) == -1){
styleDefinition = classes[x].selectorText + "{" + styleDefinition + "}";
}
arStylesWithCSSSelector.push({"selectorText":classes[x].selectorText, "styleDefinition":styleDefinition});
}
}
}
}
if(arStylesWithCSSSelector.length==0) {
return null;
}else {
return arStylesWithCSSSelector;
}
}
In addition, I've made a function which collects the css style definitions to the sub-tree of a root node your provide (through a jquery selector).
function getAllCSSClassDefinitionsForSubtree(selectorOfRootElement){
//stack in which elements are pushed and poped from
var arStackElements = [];
//dictionary for checking already added css class definitions
var existingClassDefinitions = {}
//use jquery for selecting root element
var rootElement = $(selectorOfRootElement)[0];
//string with the complete CSS output
var cssString = "";
console.log("Fetching all classes used in sub tree of " +selectorOfRootElement);
arStackElements.push(rootElement);
var currentElement;
while(currentElement = arStackElements.pop()){
currentElement = $(currentElement);
console.log("Processing element " + currentElement.attr("id"));
//Look at class attribute of element
var classesString = currentElement.attr("class");
if(typeof classesString != 'undefined'){
var arClasses = classesString.split(" ");
//for each class in the current element
for(var i=0; i< arClasses.length; i++){
//fetch the CSS Styles for a single class. Need to append the . char to indicate its a class
var arStylesWithCSSSelector = getStyleWithCSSSelector("."+arClasses[i]);
console.log("Processing class "+ arClasses[i]);
if(arStylesWithCSSSelector != null){
//console.log("Found "+ arStylesWithCSSSelector.length + " CSS style definitions for class " +arClasses[i]);
//append all found styles to the cssString
for(var j=0; j< arStylesWithCSSSelector.length; j++){
var tupleStyleWithCSSSelector = arStylesWithCSSSelector[j];
//check if it has already been added
if(typeof existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] === "undefined"){
//console.log("Adding " + tupleStyleWithCSSSelector.styleDefinition);
cssString+= tupleStyleWithCSSSelector.styleDefinition;
existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] = true;
}else {
//console.log("Already added " + tupleStyleWithCSSSelector.styleDefinition);
}
}
}
}
}
//push all child elments to stack
if(currentElement.children().length>0){
arStackElements= arStackElements.concat(currentElement.children().toArray());
}
}
console.log("Found " + Object.keys(existingClassDefinitions).length + " CSS class definitions");
return cssString;
}
Note that if a class is defined several times with the same selector, the above function will only pick up the first.
Python script to search css file for a word once found read what is inbetween the curly braces. Quick and dirty way**

two delimiters output formatting javascript

I thought this would be easier, but running into a weird issue.
I want to split the following:
theList = 'firstword:subwordone;subwordtwo;subwordthree;secondword:subwordone;thirdword:subwordone;subwordtwo;';
and have the output be
firstword
subwordone
subwordtwo
subwordthree
secondword
subwordone
thirdword
subwordone
subwordtwo
The caveat is sometimes the list can be
theList = 'subwordone;subwordtwo;subwordthree;subwordfour;'
ie no ':' substrings to print out, and that would look like just
subwordone
subwordtwo
subwordthree
subwordfour
I have tried variations of the following base function, trying recursion, but either get into infinite loops, or undefined output.
function getUl(theList, splitOn){
var r = '<ul>';
var items = theList.split(splitOn);
for(var li in items){
r += ('<li>'+items[li]+'</li>');
}
r += '</ul>';
return r;
}
The above function is just my starting point and obviously doesnt work, just wanted to show what path I am going down, and to be shown the correct path, if this is totally off base.
It seems you need two cases, and the difference between the two is whether there is a : in your string.
if(theList.indexOf(':') == -1){
//Handle the no sublist case
} else {
//Handle the sublist case
}
Starting with the no sublist case, we develop the simple pattern:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
//Add your element to your list
}
Finally, we apply that same pattern to come up with the implementation for the sublist case:
var elements = theList.split(';');
for(var i = 0; i < elements.length; i++){
var element = elements[i];
if(element.indexOf(':') == -1){
//Add your simple element to your list
} else {
var innerElements = element.split(':');
//Add innerElements[0] as your parent element
//Add innerElements[1] as your child element
//Increment i until you hit another element with ':', adding the single elements each increment as child elements.
//Decrement i so it considers the element with the ':' as a parent element.
}
}
Keep track of the current list to add items to, and create a new list when you find a colon in an item:
var baseParent = $('ul'), parent = baseParent;
$.each(theList.split(';'), function(i, e) {
if (e.length) {
var p = e.split(':');
if (p.length > 1) {
baseParent.append($('<li>').append($('<span>').text(p[0])).append(parent = $('<ul>')));
}
parent.append($('<li>').text(p[p.length - 1]));
}
});
Demo: http://jsfiddle.net/Guffa/eWQpR/
Demo for "1;2;3;4;": http://jsfiddle.net/Guffa/eWQpR/2/
There's probably a more elegant solution but this does the trick. (See edit below)
function showLists(text) {
// Build the lists
var lists = {'': []};
for(var i = 0, listKey = ''; i < text.length; i += 2) {
if(text[i + 1] == ':') {
listKey = text[i];
lists[listKey] = [];
} else {
lists[listKey].push(text[i]);
}
}
// Show the lists
for(var listName in lists) {
if(listName) console.log(listName);
for(var j in lists[listName]) {
console.log((listName ? ' ' : '') + lists[listName][j]);
}
}
}
EDIT
Another interesting approach you could take would be to start by breaking it up into sections (assuming text equals one of the examples you gave):
var lists = text.match(/([\w]:)?([\w];)+/g);
Then you have broken down the problem into simpler segments
for(var i = 0; i < lists.length; i++) {
var listParts = lists[i].split(':');
if(listParts.length == 1) {
console.log(listParts[0].split(';').join("\n"));
} else {
console.log(listParts[0]);
console.log(' ' + listParts[1].split(';').join("\n "));
}
}
The following snippet displays the list depending on your requirements
var str = 'subwordone;subwordtwo;subwordthree;';
var a = []; var arr = [];
a = str;
var final = [];
function split_string(a){
var no_colon = true;
for(var i = 0; i < a.length; i++){
if(a[i] == ':'){
no_colon = false;
var temp;
var index = a[i-1];
var rest = a.substring(i+1);
final[index] = split_string(rest);
return a.substring(0, i-2);
}
}
if(no_colon) return a;
}
function display_list(element, index, array) {
$('#results ul').append('<li>'+element+'</li>');
}
var no_colon_string = split_string(a).split(';');
if(no_colon_string){
$('#results').append('<ul><ul>');
}
no_colon_string.forEach(display_list);
console.log(final);
working fiddle here

getElementsByClassName IE resolution issue

I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is
function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");
//Loop through those items
for (var i = 0; i < list.length; ++i) {
//Reset all class names to description
list[i].className = "description";
}
if (e.className == "description"){
//Set the css class for the clicked element
e.className += " show";
}
else{
if (e.className == "description show"){
return;
}
}}
and I am using it on this page dev.msmnet.com/services/practice-management to show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.
I was curious to see what a jQuery version of your function would look like, so I came up with this:
function showDesc(name) {
var e = $("#" + name);
$(".description.show").removeClass("show");
if(e.attr("class") == "description") {
e.addClass("show");
} else if(e.hasClass("description") && e.hasClass("show")) {
return;
}
}
This should support multiple classes.
function getElementsByClassName(findClass, parent) {
parent = parent || document;
var elements = parent.getElementsByTagName('*');
var matching = [];
for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
matching.push(elements[i]);
}
}
return matching;
}
You can pass in a parent too, to make its searching the DOM a bit faster.
If you want getElementsByClassName('a c') to match HTML <div class="a b c" /> then try changing it like so...
var elementClasses = elements[i].className.split(/\s+/),
matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
found = 0;
for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {
if (matchClasses.indexOf(elementClasses[j]) > -1) {
found++;
}
}
if (found == matchClasses.length) {
// Push onto matching array
}
If you want this function to only be available if it doesn't already exist, wrap its definition with
if (typeof document.getElementsByClassName != 'function') { }
Even easier jQuery solution:
$('.service').click( function() {
var id = "#" + $(this).attr('id') + 'rt';
$('.description').not(id).hide();
$( id ).show();
}
Why bother with a show class if you are using jQuery?
Heres one I put together, reliable and possibly the fastest. Should work in any situation.
function $class(className) {
var children = document.getElementsByTagName('*') || document.all;
var i = children.length, e = [];
while (i--) {
var classNames = children[i].className.split(' ');
var j = classNames.length;
while (j--) {
if (classNames[j] == className) {
e.push(children[i]);
break;
}
}
}
return e;
}
I used to implement HTMLElement.getElementByClassName(), but at least Firefox and Chrome, only find the half of the elements when those elements are a lot, instead I use something like (actually it is a larger function):
getElmByClass(clm, parent){
// clm: Array of classes
if(typeof clm == "string"){ clm = [clm] }
var i, m = [], bcl, re, rm;
if (document.evaluate) { // Non MSIE browsers
v = "";
for(i=0; i < clm.length; i++){
v += "[contains(concat(' ', #"+clc+", ' '), ' " + base[i] + " ')]";
}
c = document.evaluate("./"+"/"+"*" + v, parent, null, 5, null);
while ((node = c.iterateNext())) {
m.push(node);
}
}else{ // MSIE which doesn't understand XPATH
v = elm.getElementsByTagName('*');
bcl = "";
for(i=0; i < clm.length; i++){
bcl += (i)? "|":"";
bcl += "\\b"+clm[i]+"\\b";
}
re = new RegExp(bcl, "gi");
for(i = 0; i < v.length; i++){
if(v.className){
rm = v[i].className.match(bcl);
if(rm && rm.length){ // sometimes .match returns an empty array so you cannot use just 'if(rm)'
m.push(v[i])
}
}
}
}
return m;
}
I think there would be a faster way to iterate without XPATH, because RegExp are slow (perhaps a function with .indexOf, it shuld be tested), but it is working well
You can replace getElementsByClassName() with the following:
function getbyclass(n){
var elements = document.getElementsByTagName("*");
var result = [];
for(z=0;z<elements.length;z++){
if(elements[z].getAttribute("class") == n){
result.push(elements[z]);
}
}
return result;
}
Then you can use it like this:
getbyclass("description") // Instead of document.getElementsByClassName("description")

Categories