0

Been trying for hours, but can't get this to work.

If I go direct

$(.button).click(function(event){
    var graham = window.document.childNodes[1].childNodes[2].childNodes[1].childNodes[9];
    $(graham).css('color', 'red');
)};

But instead of just typing out the DOM node directly, if I cycle it through a loop like:

$(.button).click(function(event) {
  js = (js.slice(0, -1)).split(",");
  for(x = 0; x< js.length; x++) {
      js[x] = "childNodes[" + js[x] + "]";
  }
  js = "window.document." + js.join(".");
    $(js).css('color', 'red');

)};

Nothing happens onclick. Is there something wrong with using 'window.document' as a string and appending it to the childNodes data? I thought this would be straight forward, but can't get it to work!..

Graham T
  • 968
  • 9
  • 14

2 Answers2

1

The problem is that jQuery sees js as a string not an object :

This changes the Stackoverflow website <body> to green :

$(window.document.childNodes[1].childNodes[2]).css('background', 'green');

This doesn't :

$('window.document.childNodes[1].childNodes[2]').css('background', 'green');

However this does :

$(eval('window.document.childNodes[1].childNodes[2]')).css('background', 'green');

Try it in your console.

You need to do :

$(eval(js)).css('color', 'red');
Sparkup
  • 3,686
  • 2
  • 36
  • 50
  • Perfect! Thank you! I knew it was something simple and stupid related to using strings for the DOM structure. Thanks for taking the time to write out code examples, much appreciated. – Graham T Feb 27 '14 at 02:09
0

If you are already using jQuery it is not necessary to search nodes with the native NodeList object via childNodes. Just rely on a jQuery selector.

If jQuery is not used, you can rely on native DOM methods such as querySelector, getElementById, getElementsByTagName, getElementsByClassName, etc.

clonyx
  • 11
  • 2
  • I know. I'm building this piece to handle a universal set of use cases though. I can't assume the element has a class or ID, or any marker. And I also need to target the exact node, not ALL

    's, or ALL 's for example

    – Graham T Feb 27 '14 at 02:02