Reputation: 6694
I would like to know if an element contains any text directly. By directly I mean: not through its children.
<div id="case1"></div>
<div id="case2">text-in-div</div>
<div id="case3">
<p>text-in-p</p>
</div>
<div id="case4">
text-in-div
<p>text-in-p</p>
</div>
<div id="case5">
<p>text-in-p</p>
text-in-div
</div>
<div id="case6">
<p>text-in-p</p>
text-in-div
<p>text-in-p</p>
</div>
<script>
function containsTextDirectly(id) {
var element = document.getElementById(id);
//what comes here?
}
console.log(containsTextDirectly("case1")); //false
console.log(containsTextDirectly("case2")); //true
console.log(containsTextDirectly("case3")); //false
console.log(containsTextDirectly("case4")); //true
console.log(containsTextDirectly("case5")); //true
console.log(containsTextDirectly("case6")); //true
</script>
Obviously I could check it programmatically (remove children and see if the elements becomes empty..) but I am searching for a more optimal (elegant) solution.
Upvotes: 0
Views: 1245
Reputation:
Check for text nodes directly under the element:
return Array.prototype.some.call(element.childNodes, function(child) {
return child.nodeType === Node.TEXT_NODE;
})
If you want to make sure the text nodes are non-empty (to give the "correct" answer in your case3) then
return child.nodeType === Node.TEXT_NODE && /\S/.test(child.nodeValue);
where /\S/.test
tests for the presence of at least one non-white-space character.
Upvotes: 6
Reputation: 366
if you just want “ Any String ” and wants to ignore all the child element? Well, here is a simple solution using jQuery.
<script>
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text(); //get the text of element
</script>
We clone the element that you want text of, then remove all the child elements from this cloned element and then returns the text of element.
Upvotes: 0