Refaat
Refaat

Reputation: 107

how to get a string contained in a div

I have a div that contains div in HTML code, i just want to retrieve the string contained in that div, like the word LATTE or price:12 in the next code:

<!DOCTYPE html>
<html>
    <head>
        … 
    </head>
    <body>
        <div id="items">
            <div id="heapbox_46958322" class="heapBox">
                …
            </div>
            <select class="basic-example" style="display: none;">
                … 
            </select>
            <div id="dummy">
                …
            </div>
            <div id="gallery">
                <div class="item_block">
                    …
                </div>
                <div class="item_block">
                    …
                </div>
                <div class="item_block hasoptions">
                    price:12
                <div class="add_btn">
                </div>
                <div class="item_name">
                    LATTE
                </div>
            </div>
        </div>
        <div id="order_list">
            …
        </div>
    </div>
    <script type="text/javascript">
        …
    </script>
</body>

Fiddle Here

The answers help me get all the texts in all the divs that called item_Name , but i want it from the div i clicked as i'm using an onlclick event :

$('.item_block').on('click',function(){

// here is the tip

document.getElementsByClassName("add_btn").onclick =
    alert($(".item_name").text());    
.
.
.

Upvotes: 0

Views: 2547

Answers (5)

J_Goodman
J_Goodman

Reputation: 36

innerText on the object should allow you to not only retrieve but also overwrite the text

Upvotes: 0

Jon
Jon

Reputation: 976

You can use jQuery's .text() function.

Example:

$(".item_name").text();

This will retrieve the text inside all divs with the class item_name.

If you just want the text of the .item_name that you clicked on:

$(".item_name").click(function() {
  $(this).text();
});

Demo: http://jsfiddle.net/UFMkQ/1/

Upvotes: 2

Nishad K Ahamed
Nishad K Ahamed

Reputation: 1394

You could use innerHTML attribute of div to get the text inside.

alert(document.getElementById('divid').innerHTML);

Upvotes: 0

S. S. Rawat
S. S. Rawat

Reputation: 6111

Try this, this is help to you, In this i just add text to your order_list div for how to add text in div

$('#order_list').html('XYZ');

Fiddle Here

Upvotes: 0

Voonic
Voonic

Reputation: 4775

Give that div a id

suppose id="getText"

In javascript

var value = document.getElementById('getText').innerText || document.getElementById('getText').textContent;

Upvotes: 2

Related Questions