Jamie
Jamie

Reputation: 2081

How to use div class text in javascript?

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.

Upvotes: 0

Views: 1822

Answers (3)

Bankzilla
Bankzilla

Reputation: 2096

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()

Upvotes: 1

cube
cube

Reputation: 1802

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/

Upvotes: 0

jdrm
jdrm

Reputation: 621

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");

Upvotes: 1

Related Questions