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!..

4
  • 3
    $(.button) should be $('.button') Commented Feb 27, 2014 at 0:12
  • 2
    what is the value of variable js Commented Feb 27, 2014 at 0:13
  • Seems like you should be able to easily answer your own question using the developer tools of your favorite browser. Set a breakpoint on the click event handler and step through the code. Commented Feb 27, 2014 at 0:16
  • 1
    The problem is that jQuery sees js as a string not an object Commented Feb 27, 2014 at 0:32

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

1 Comment

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 <p>'s, or ALL <a>'s for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.