0

This $("#grid_modal div")[0].childNodes[0] captures all the text in a given div. But how come adding .select() to the end causes an error?

$("#grid_modal div")[0].childNodes[0].select()
//TypeError: Object #<Text> has no method 'select'

Text has not method select? How can I get around this?

1252748
  • 14,597
  • 32
  • 109
  • 229
  • Because by adding `[0]` you're getting the DOM node, not the jQuery object, and then you're trying to use jQuery again (`.select()`) on the DOM node. That's like trying to do `document.getElementById('foo').closest('tr')`. – j08691 Nov 05 '13 at 18:35
  • are you trying to get all the text in a div, or start a selection around all text in a given div bc the latter i think you'll need to make content editable. – Jay Harris Nov 05 '13 at 19:05

2 Answers2

0

As soon as you do [0] on the jQuery Object, you've effectly left your jQuery environment for a vanilla Node. This means you can't use jQuery's methods, without re-applying it.

var node = $("#grid_modal div")[0].childNodes[0];
$(node).select();

This [...] captures all the text in a given div

You're actually getting the first Node which is a child of the first Node of your #grid_modal div, there is no guarantee that this is a text node. If you want text, it may be better to use node.textContent

Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

You are attempting to call the select Javascript method.

For an Input or TextArea element, this will focus the element and select all the text in it.

However you haven't got an input or a textarea element. You've actually got a text node. You were trying to find the first child element of the div, but there was a text node before it, and text nodes are selected when you do childNodes.

The easy way round this is to use jQuery to do the whole selection instead:

$("#grid_modal div").eq(0).children().first()[0].select()

You can do it with vanilla Javascript instead. For instance, you can use the children property, but this isn't available across all browsers (in particular in IE<9).

$("#grid_modal div")[0].children[0].select()
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • Thanks, but this is giving me `TypeError: Cannot call method 'select' of undefined`. The structure is `
    text to select
    `. Any ideas?
    – 1252748 Nov 05 '13 at 18:45
  • 1
    Elements other than `input` and `textarea` elements don't have a `select` method. What do you want to do? Highlight the text? If so, have a look at [this question](http://stackoverflow.com/questions/1173194/select-all-div-text-with-single-mouse-click). – lonesomeday Nov 05 '13 at 18:45