Doron Cohen
Doron Cohen

Reputation: 245

getting text content of specific element

I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:

<p>hello <h1> World </H1> </p>

for element "P" the right output should be ONLY "hello ".

I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").

Thanks,

Upvotes: 2

Views: 770

Answers (7)

zaerymoghaddam
zaerymoghaddam

Reputation: 3117

Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.

The function below loops over all element in document and prints just #text items

function myFunction()
{
    var txt="";
    var c=document.body.childNodes;
    for (i=0; i<c.length; i++)
    {
        if(c[i].nodeName == "#text")
            txt=txt + c[i].nodeName + "<br>";
    };
    return txt;
}

EDIT:

As @VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.

Upvotes: 0

MarsOne
MarsOne

Reputation: 2186

The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.

<p >hello<h1>World</h1> </p>

This line will be rendered as

hello

World

If you look at this code it will be as follow

<p>hello</p>
<h1>World</h1> 
<p></p>

With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element. Check this article

Now you can select the content of the first p tag simply by using the following code

var p = document.getElementsByTagName('p');
console.log(p[0].textContent);

JS FIDDLE

Upvotes: 1

pawel
pawel

Reputation: 36965

Considering this HTML:

<div id="gettext">hello <p> not this </p> world?</div>

do you want to extract "hello" AND "world"? if yes, then:

var div = document.getElementById('gettext'), // get a reference to the element
    children = [].slice.call(div.childNodes), // get all the child nodes
                                              // and convert them to a real array  
    text = children.filter(function(node){
        return node.nodeType === 3;           // filter-out non-text nodes
    })
    .map(function( t ){ 
        return t.nodeValue;                   // convert nodes to strings 
    });    

console.log( text.join('') );                 // text is an array of strings.

http://jsfiddle.net/U7dcw/

Upvotes: 3

user2700307
user2700307

Reputation: 130

Try to provide id for the element which you want to do some operation with that.

Below is the working example, it show output as "hello" as you expected.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
   alert(document.getElementById('test').innerHTML);

}
</script>
</head>

<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>

</html>

Upvotes: 0

Sara
Sara

Reputation: 272

Change your html to

<p id="id1">hello <h1> World </h1> </p>

Use this script,

alert(document.getElementById("id1").firstChild.nodeValue);

Upvotes: 0

Netorica
Netorica

Reputation: 19327

well behind it is an explanation

 $("p").clone()   //clone element
        .children() //get all child elements
        .remove()   //remove all child elements
        .end()  //get back to the parent
        .text();

Upvotes: 1

Simone
Simone

Reputation: 21262

You can use the childNodes property, i.e.:

var p = document.querySelector('p');
p.childNodes[0]; // => hello

jsFiddle

Upvotes: 0

Related Questions