views:

279

answers:

3

I am trying to create a function that given a divid, and a list of classes, will then do some text replacing inside them.

Having learned of how Firefox Dom is handling text nodes differently, I read that I had to use javascript to loop through the elements, sibling to nextSibling.

The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced.

Having looked all the answers, and with the help of a co-worker named Ryan at work, we have redone this in jquery.

        $(divid).find(".status_bar").each( function() {
        var value = $.trim($(this).text());
        // if value is not defined thru browser bugs do not replace
        if (typeof(value) != 'undefined') {
            // it is a text node. do magic.
            for (var x = en_count; x > 0; x--) {
                // get current english phrase
                var from = en_lang[x];
                // get current other language phrase
                var to = other_lang[x];
                if (value == from) {
                    console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
                    value = to;
                    $(this).attr('value', to);
                }
            }
        }
    });

This currently works in all areas, except in the replacing of text.

The reason I had originally with doing this in jQuery, had to be not sure I could loop thru elements, and avoid the problem with firefox and text nodes.

I am doing a loop of all elements inside a div, and I now need to get the classname of the element that I am looping by.

Then i can check if the current element's class is one, I need to do something with...

 // var children = parent.childNodes, child;
    var parentNode = divid;

    // start loop thru child nodes
    for(var node=parentNode.firstChild;node!=null;node=node.nextSibling){

    var myclass = (node.className ? node.className.baseVal : node.getAttribute('class'));

    }

But this code for getting the classname only get's null values.

Any suggestions?

For those of you who are trying to figure out what the whole point is, read this JavaScript NextSibling Firefox Bug Fix I have code that does my language translation that works in Google Chrome and IE. But when I use it in Firefox, and try to translate div content after ajax has loaded it, it fails because of the whitespace issue.

I really don't have a preference of jQuery or Pure Javascript, I just want a working solution.

Thank you all for being patient. I personally thought I was extremely clear in my description, I apologize if it wasn't. I wasn't trying to be obscure or make it difficult to get help. But please don't insult me, by implying I am trying to make it unclear.

Thanks.

+2  A: 

Hm... You have jQuery but don't use it?

$(divid).children(".yourSpecialClassName").each( function() {
  doSomethingWith(this);
});

To get the CSS class attribute value, this will do:

$(divid).children().each( function() {
  alert(this.className);
});

Based on the function you posted now, you want this:

$(divid).find(".status_bar").each( function() {
  $(this).text( function(i, text) {
    var x = $.inArray(en_lang, $.trim(text));
    if (x > -1) {
      console.log('Current Value ['+text+'] English ['+en_lang[x]+'] Translation ['+other_lang[x]+']');
      return other_lang[x];
    }
    return text;
  });
});

And please, don't ever use "do magic" as a comment again. This is incredibly lame.


EDIT. This can be made much more efficient (superfluous console.log() removed):

$(divid).find(".status_bar").each( function() {
  // prepare dictionary en_lang => other_lang
  var dict = {};
  $.each(en_lang, function(x, word) { dict[word] = other_lang[x]; });

  $(this).text( function(i, text) {
    var t = $.trim(text);
    return (t in dict) ? dict[t] : text;
  });
});
Tomalak
How do i get the classname of the node inside my loop? I have to loop thru all elements inside a div. But I can not loop numerically thru because that doesn't work in firefox, so this script is to loop thru each element inside the div, and then let me do something..Can you help?
crosenblum
@crosenblum: You are too vague. Don't tell me what you are trying to *do* ("lift my leg and then lift my other leg and so on") but what you are trying to *achieve* ("reach the other end of the room"). Best, add sample HTML to your question and identify the elements you want to work on. Hint: You *sure as hell* don't need any for loop around `firstChild` and `nextSibling` DOM properties when you have jQuery.
Tomalak
What I am trying to do is, loop through elements of content inside a div, but I can't use my numerical looping because of Firefox's dom handling. That's why I was trying to do it via javascript.
crosenblum
@crosenblum: You are *still* not telling me what you are trying to do. I'm not even sure why you make such an effort navigating around browser incompatibilities - jQuery does all of that for you. If you still have to do stuff like that, it is a strong indicator that you're doing it wrong. And that means: Tell us what you want to do, not how you want to do it. Is that so hard?
Tomalak
Love the way you used `.inArray` and a text replacement function. I got lazy in my answer. ;) I *think* from his question he wants to replace text which has both a status_bar and some_other_class, but otherwise and elegant solution.
ghoppe
@ghoppe: Thanks. It's hard to tell what he wants because he just won't say… ;) - BTW I've added a dictionary based solution.
Tomalak
I am creating a firefox only function to do language translation, but only inside a few classes inside a div, that content loaded into it via ajax. I am not trying to avoid saying it, it's just not easy to explain.
crosenblum
The comment was from code that I took from somewhere else on stackoverflow...
crosenblum
+1  A: 

if you are using jquery you can do this:

$("#myDiv").find("*").each(
   function(){
      var myclass = $(this).attr("class");
   }
);
Luis
That's not going to work in this case...So please just answer my question please.
crosenblum
Why it's not going to work? You are not using jquery? When you say all element, you mean all as in recursive or all as in just the direct child elements of the div?
Luis
+1  A: 

Your sample code doesn't make sense.

$(this).attr('value', to);

'value' is an attribute of the tag, not the text content.

Did you really mean to do this instead?

$(this).text(to);

Also, you've re-edited your question, but you're still trying to loop through the child nodes using non-jQuery methods. You said "The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced."

If you are using jQuery it is completely unnecessary to loop through anything to get a class name. You simply have to use a proper selector in the first place.

 $(divid).find(".status_bar.replaceme").each( function() {  
    // .replaceme is whatever class you're using for the stuff you want to change
    // .status_bar.replaceme matches all elements with BOTH status_bar and replaceme classes

    var value = $.trim($(this).text());
    // if value is not defined thru browser bugs do not replace
    if (typeof(value) != 'undefined') {
        // it is a text node. do magic.


        // NOTE: The following is inefficient but I won't fix it. 
        //       You're better off using an associative array

        for (var x = en_count; x > 0; x--) {
            // get current english phrase
            var from = en_lang[x];
            // get current other language phrase
            var to = other_lang[x];
            if (value == from) {
                console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
                // value = to;    <-- useless, get rid of it.
                $(this).text(to);
                // or $(this).html(to);
            }
        }
    }
});
ghoppe
I need to replace some text inside the html, but without losing the rest of the html.
crosenblum
This is not logical. You won't lose the rest of the html, only any html inside your replacement class element. If you are replacing english text with translated text, how do you propose to replace it without replacing the inline html? You would have to know the context ie. `<p>My <em>favourite</em> name is Bob.</p>` would need to be replaced with `<p>Meu nome <em>preferido</em> é Bob.</p>` How do you propose to replace it contextually?
ghoppe
If you are only replacing *part* of your class-selected element, then your entire methodology is wrong. You're matching the entire `.text()` contents (minus leading/trailing spaces) of your element to be replaced with the translated text in an array.
ghoppe
@ghoppe: \*sigh\* I'm giving up on this. I can't do more than I have done in my answer.
Tomalak
@Tomalak you've gone above and beyond the call of duty, good sir! :)
ghoppe
When I replace a href link that contains the word "Print" with the word "Imprinter" it changes it from a link to just text. I am trying to avoid that.
crosenblum