Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the contents of an element WITHOUT its children

Tags:

I have a mild preference in solving this in pure JS, but if the jQuery version is simpler, then jQuery is fine too. Effectively the situation is like this

<span id="thisone">
 The info I want
 <span id="notthisone">
  I don't want any of this nonsense
 </span>
</span>

I effectively want to get
The info I want
but not
The info I want I don't want any of this nonsense
and I especially don't want
The info I want <span id="notthisone"> I don't want any of this nonsense </span>
which is unfortunately what I am getting right now...

How would I do this?

like image 562
Mala Avatar asked Jul 03 '10 17:07

Mala


People also ask

How do you remove all children from an element?

To remove all child nodes of an element, you can use the element's removeChild() method along with the lastChild property. The removeChild() method removes the given node from the specified element. It returns the removed node as a Node object, or null if the node is no longer available.

How do you find the elements of children?

To get the children of an element, you use the childNodes property of the element. How it works: First, select the element whose id is container using the querySelector() method. Then, use the childNodes property to get the children of the container elements.

What is the difference between element childNodes and element children?

The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes.


2 Answers

With js only:

Try it out: http://jsfiddle.net/g4tRn/

var result = document.getElementById('thisone').firstChild.nodeValue;    

​alert(result);​

With jQuery:

Try it out: http://jsfiddle.net/g4tRn/1

var result = $('#thisone').contents().first().text();  

alert(result);​

Bonus:

If there are other text nodes in the outer <span> that you want to get, you could do something like this:

Try it out: http://jsfiddle.net/g4tRn/4

var nodes = document.getElementById('thisone').childNodes;
var result = '';

for(var i = 0; i < nodes.length; i++) {
    if(nodes[i].nodeType == 3) {       // If it is a text node,
        result += nodes[i].nodeValue;  //    add its text to the result
    }
}

alert(result);
​
like image 116
user113716 Avatar answered Sep 19 '22 00:09

user113716


If you just want the first child then it's rather simple. If you are looking for the first text-only element then this code will need some modification.

var text = document.getElementById('thisone').firstChild.nodeValue;
alert(text);
like image 27
Jason McCreary Avatar answered Sep 22 '22 00:09

Jason McCreary