user2010541
user2010541

Reputation: 13

Access normal text using jquery

I have the following HTML code:

<div class="top_l">
    <a class="shou" onclick="" href="">11</a> | 
    <img border="0" class="" src="/">XXXXXX<a href=""></a> | 
    <a href=""></a> | 
    <a href=""></a> 
</div> 

How do I get the text XXXXXX using jQuery(what selector to be used)?

Upvotes: 0

Views: 120

Answers (4)

arjuncc
arjuncc

Reputation: 3287

You have plenty of solution, I add one more :)

var divVar=$(".top_l").clone();
divVar.children().addClass("remove");
divVar.children().remove(".remove");
var txt=divVar.html();
txt=txt.replace (/\|/g, '');

JSFIDDLE

Upvotes: 0

Avinash R
Avinash R

Reputation: 3151

you can do like this:

var childNodes = document.querySelector("div").childNodes, pickNext = false;
for(var i in childNodes) {
    var childNode = childNodes[i];
    if(pickNext) {
        alert(childNode.nodeValue);
        break;
    }
    // same as $(childNode).is("img")
    // now you can put the XXXXXX where ever you want.
    // as far as you know which is the next sibling.you can get it
    if(childNode.nodeName === "IMG") {
        pickNext = true;
    }
}

by this way you can find the text anywhere it is as long as you know the sibling's node type.

DISCLAIMER: this may not work in IE.

DEMO

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816580

You can only select element nodes with jQuery. And most jQuery methods only consider element nodes, so using jQuery and plain DOM API together might be a good approach here.

The text node you want to target is the next sibling of the image. So if you can get a reference to the image element, you can access the text node with the .nextSibling [MDN] property:

var txt = image.nextSibling.nodeValue;
// or if image is a jQuery object
var txt = image.get(0).nextSibling.nodeValue;

Given the structure of the HTML, you could do something like this:

var txt = $('.top_l > img').get(0).nextSibling.nodeValue;

DEMO

Upvotes: 2

KlipJan
KlipJan

Reputation: 21

Well, you have to put it inside an html tag and call that tag using jquery, see sample below.

<img src = "abcd.png" /> <span>XXXXXX</span> <br />etc etc<and some more HTML code>

and in your jquery

$(document).ready(function(){
alert($("span").text());
});

in jquery you can use css selectors to select the tag

<img src = "abcd.png" /> <span id="theText">XXXXXX</span> <br />etc etc<and some more HTML code>

$(document).ready(function(){
alert($("#theText").text());
});

Upvotes: 0

Related Questions