dropWizard
dropWizard

Reputation: 3538

Select the text from a CSS selector using jQuery (or javascript)

Running this in the console:

$('#background-experience h4 a')

Returns a list of:

<a href='someURL.com' name='something' title='title class='class>SOME TEXT</a>

How do I select the first element from the list and then "SOME TEXT"?

$('#background-experience h4 a').text() 

returns all of the "SOME TEXT". But

$('#background-experience h4 a')[0].text() 

breaks with this error:

$('#background-experience h4 a')[0].text()
Uncaught TypeError: string is not a function

Upvotes: 1

Views: 91

Answers (2)

Ashish
Ashish

Reputation: 743

$('#background-experience h4 a').text();

To select the first element from the list and then "SOME TEXT-

$('#background-experience h4 a:eq(0)').text()

Upvotes: 5

henser
henser

Reputation: 3327

jQuery solution:

Use the .text() method like this:

$('#background-experience h4 a').text();

Pure JS solution:

Use innerHTML() like:

document.getElementsByName('something')[0].innerHTML;

This is just a selector sample. There are multiple ways to select an element.

If you want to select the first occurance of an element you can use the css selector :first-child or the method .eq(0) after the jquery selector

Upvotes: 0

Related Questions