0

As of now I am able to retrive the alt text from an image but I am also trying to retrive the text from a div class to display depending on the image. This is the script I am using to retrive the alt text

      var title = $i.attr( 'alt' );
        $('#title').text( title );

Now how do I replace the .attr is it .div? I am new to javascript. Any help would be appreciated.

1
  • I dunno what jQuery calls it, but you'd ask for the div's innerText or innerHTML. Commented Nov 12, 2012 at 1:53

3 Answers 3

1

There's a few ways you can do it, it depends on wether you want all the styles inside the div as well.

<div id="subject"><span>Hello</span> world!</div>​

var text = $('#subject').text(); //Will return only the text with #subject
var html = $('#subject').html(); //Will return all tags. eg <span></span>

Fiddle demonstrating it working

Documentation on .text()

Documentation on .html()

Sign up to request clarification or add additional context in comments.

Comments

1

If what you are looking is to be able to get and set the class of a div:

Get the class from your div:

var myClass = $('#title').attr('class');

Set the class (assuming you only want to have one class for the div)

$('#title').attr("class","someClassYouWantToSet");

2 Comments

She's wanting to get the text within a div.
"How to use div class text in javascript?" confusing question :P
0

You can use innerHTML this way:

var myTextDiv = document.getElementById('divID');
console.log(myTextDiv.innerHTML)
​

Or using jQuery:

console.log( $('divID').innerHTML )

See it live: http://jsfiddle.net/scMXx/3/

Comments

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.