How to get div text value? - javascript

I've got the following html:
<div class="question">
<div class="text">
Blah Blah
</div>
</div>
I am trying to get the value "Blah Blah" using javascript.
So something like?
alert(document.getElementsByName("question")[0].value);

document.getElementsByClassName('question')[0].innerText;
or
document.querySelector('.question').innerText;

You can do it like this
alert(document.getElementsByClassName("question")[0].children[0].innerHTML);

You need to select the element correctly first. It doesn't (and can't) have a name attribute so getElementsByName is wrong. You can use getElementsByClassName or (with more limited support) the new and shiny querySelector:
var div = document.querySelector('.question');
Then you need to get it's "value". It isn't a form control so it doesn't have a value property. It has childNodes, the one of which you care about is another div.
var childDiv = div.querySelector('.text');
You can skip the two stages if you are are using querySelector and just use a descendant combinator:
var childDiv = document.querySelector('.question .text');
This child div then has another child node, but it is a text node rather than an element node. You can get it like so:
var textNode = div.firstChild;
Finally you can get the text in a textNode using the data property.
var text = textNode.data;
And if you put it all together:
alert(document.querySelector('.question .text').firstChild.data);
Such: http://jsfiddle.net/LR93S/

No need to rely on jQuery here, use innerText
document.querySelectorAll('div.question')[0].innerText

$('.question').text(); // jquery
document.getElementsByClassName("question")[0].innerText; // javascript

Try this: document.getElementsByClassName("text")[0].innerHTML (http://jsfiddle.net/hv9Dx/15/)

The simplest way to do this is with jquery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
var divvalue = $('.text').html()
alert (divvalue);
You could also change your html to use an ID
<div class="question">
<div id="text">
Blah Blah
</div>
</div>
and use:
document.getElementById("text").innerHTML;
Example: http://jsfiddle.net/DanBrown180/N9Z8Z/

document.querySelectorAll('.text')[0].innerHTML

For the following example:
<div class="question" id="question">
<div class="text" id="text">
Blah Blah
</div>
</div>
You can try to get the value of its inner div tag like this:
alert(document.getElementById('question').childNodes[1].innerHTML);
Cheers!

Use the standard DOM property textContent, which is widely supported and standardized, unlike innerText:
document.getElementsByClassName("question")[0].textContent;
If you need to support IE <= 8 then you've got two problems: neither document.getElementsByClassName() nor textContent is supported.
For the first issue, it's not too hard to write/find a function to retrieve elements by class name using other DOM methods (example).
For the second, you can use IE's innerText property, which will do roughly (but not precisely) the same thing as textContent.

Related

Javascript:: textContent/innerText of firstChild

My code is pretty much explain itself of what I'm about to get :
<div id=player>
<div class="button hand">►</div>
<div class=time>00:00/02:25</div>
<div class="timeline hand"><span class="now hand"></span></div>
</div>
<script>
var myPlayer=document.getElementById('player').firstChild;
var playerStatus=(myPlayer.innerText||myPlayer.textContent);
console.log(playerStatus);
</script>
I'm expect to get the ascii value ► on console.
Small tweak needed here
Try this:
var myPlayer=document.getElementById('player').firstElementChild;
The problem is that the first child of #player is a text node itself. What you're looking for is the first element child of #player.
A minor note: firstElementChild isn't supported by IE8-.
You have both id and class available, so use querySelector().
var myPlayer=document.querySelector('#player > .button.hand');
This also has the benefit of working in IE8.
Also, a shortcut for innerText/textContent is to check for it at the top of your script, and store the appropriate key in a string.
var text = ("textContent" in document) ? "textContent" : "innerText";
Then use square brackets with the text variable.
var myPlayer=document.querySelector('#player > .button.hand');
var playerStatus=(myPlayer[text]);
Then you can actually shorten it like this:
var playerStatus=document.querySelector('#player > .button.hand')[text];

How can I count the number of elements with same class?

I have a main div in my page with a specific id. Now some input elements of the same class are present in this div. So how can I count the number of these elements of same class in this div using jQuery?
With jQuery you can use
$('#main-div .specific-class').length
otherwise in VanillaJS (from IE8 included) you may use
document.querySelectorAll('#main-div .specific-class').length;
document.getElementsByClassName("classstringhere").length
The document.getElementsByClassName("classstringhere") method returns an array of all the elements with that class name, so .length gives you the amount of them.
You can get to the parent node and then query all the nodes with the class that is being searched. then we get the size
var parent = document.getElementById("parentId");
var nodesSameClass = parent.getElementsByClassName("test");
console.log(nodesSameClass.length);
<div id="parentId">
<p class="prueba">hello word1</p>
<p class="test">hello word2</p>
<p class="test">hello word3</p>
<p class="test">hello word4</p>
</div>
$('#maindivid').find('input .inputclass').length
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
Simplest example:
document.getElementById("demo").innerHTML = "count: " + document.querySelectorAll('.test').length;
<html>
<body>
<p id="demo"></p>
<ul>
<li class="test">Coffee</li>
<li class="test">Milk</li>
<li class="test">Soda</li>
</ul>
</body>
</html>

Retrieve text from an element and insert it somewhere else

I'd like to get the text from between the "p" tags and put it in an other element, like this:
before:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p></p>
</div>
after:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p>$1,200.00</p>
</div>
Anyone know of a Javascript that can do this?
The below function copies the contents of the first paragraph under an element with ID ID to a paragraph under another element with ID putID.
function copyContents(id) {
var source = document.getElementById(id).getElementsByTagName("p")[0];
var target = document.getElementById("put" + id).getElementsByTagName("p")[0];
target.innerHTML = source.innerHTML;
}
copyContents("Text");
you can use following jQuery code
$('#putText p').html($('#Text p').html());
If you have jQuery at your disposal, it's fairly easy - something like this should work:
$('#putText>p').text($('#Text>p').text())
If you don't, then you'll have to resort to some DOM manipulation - the same stuff jQuery does behind the scenes, only you need to code it up yourself.

Cleaner way to write element.parent().parent().parent().parent().parent()

If I need to select 10-th parent, is there a cleaner way, then repeating .parent() 10 times?
$('#element_id').parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
If there's a selector that represents the target you're after, then use .closest() or .parents().
$('#element_id').closest('.someClass');
$('#element_id').parents('.someClass:first');
...but both of these will return the first match found. The proper solution will depend on your actual HTML markup.
(Note that .closest() also evaluates the original element, while parents() starts with the first ancestor.)
Also keep in mind that browsers make HTML corrections. So if you're traversing from inside a <table> that has no <tbody> to an element outside the <table>, doing x number of .parent() may give different results in different browsers.
The following post here uses this implementation:
jQuery.fn.getParent = function(num) {
var last = this[0];
for (var i = 0; i < num; i++) {
if(!last) break;
last = last.parentNode;
}
return jQuery(last);
};
// usage:
$('#myElement').getParent(3);
so your usage would simply be:
$('#element_id').getParent(10);
If you truly need to get the 10th parent, and you are unable to use a selector to get there, the smoothest way would probably be something like this:
$('#element_id').parents().eq(9);
I've used this code:
var position = $("#test").parents("div").length - 10;
$("#test").closest("div:eq(" + position + ")").append("here!!!");
with that HTML :
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<span id="test">here</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Yes that is 11 div. so running the code should stop at the 10th div and append here!!!
I'm sure this code could be even more clean.
No need to add class.
Edit:
I used 11 DIV so you can see it's not going to the very first one, it actually stop at the 10th.

jquery Remove siblings elements, doesn't work in IE7

I'm trying to remove all the sibling elements after a particular div, lets say the div tag with id = id8.
<form>
<div id="id5">something ...<div>
<div id="id8">something ...<div>
<div id="id3">something ...<div>
<div id="id97">something ...<div>
<div id="id7">something ...<div>
...
<div id="idn">some text ...<div>
</form>
To do that I use the following code in jquery.
$("#id8 ~ div").remove();
It works fine in Firefox, but It doesn't work in IE7.
Is there an alternative way to archieve this, using jquery and just giving the tag id from the element I want to start removing the elements?
Thanks
Thanks everybody for your help
I end up with this solution based on the accepted answer
function removeAfter(el,tag){
element = $('#'+el);
var aElements = $(tag,element.parent());
var index = (aElements.index(element));
for(i=(index+1);i<aElements.length;i++) {
$('#'+$(aElements.get(i)).attr('id')).remove();
}
}
just call
removeAfter('id8', 'div')
Two things!
1) Close your <div> tags! It should look like this:
<form>
<div id="id5">something ...</div>
<div id="id8">something ...</div>
<div id="id3">something ...</div>
<div id="id97">something ...</div>
<div id="id7">something ...</div>
<div id="idn">some text ...</div>
</form>
2) The ~ operator only matches siblings that follow the matched element (ie it will match id3, id97, id7 and idn, but not id5). To match every sibling, including id5, you do this:
$("#id8").siblings("div").remove();
That should leave you with just id8. I tested this in Firefox 3.5.5 and IE7.0something. Hope that helps!
Three steps here:
Find the index number of the element we've clicked, with respect to its parent.
Loop through all the div elements contained within this parent, starting after the one we just found
Delete each div found
$(document).ready(function(){
$('#parent').children().click(function(){
var index = ($('div',$(this).parent()).index(this));
for(i=(index+1);i<$('div',$(this).parent()).length;i++){
$($('div',$(this).parent()).get(i)).hide();
}
});
});
This will work on this HTML
<div id="parent">
<div id="c1">c1</div>
<div id="c2">c2</div>
<div id="c3">c3</div>
<div id="c4">c4</div>
<div id="c5">c5</div>
</div>
Comment here if you've got any more problems on the matter!
P.S. An application of this solution exact to your request is the following
function removeAfter(el){
element = $('#'+el);
var index = ($('*',element.parent()).index(element));
for(i=(index+1);i<$('*', element .parent()).length;i++){
$($('*', element.parent()).get(i)).hide();
}
};
EDIT:
Editing the answer below to add what should be a fix for the problem:
$("#id8").nextAll().remove();
END EDIT.
Ok. This appears to be an interesting bug - initial testing seems to indicate it's a jquery bug although I haven't found any specific mention of it anywhere.
The bug seems to be that if your initial selector tag is the same type as its siblings then it will fail to return any siblings in IE7.
I tested it using the jQuery example code for the selector itself and was able to duplicate your problem in IE8 emulating IE7.
If you check the jquery example code I'll stick below you can see that the actual element they're using as the initial selector is a span and the sibling elements are all divs whcih seems to me to indicate they know about this bug and haven't documented it, which is both cunning and shitty.
<script>
$(document).ready(function(){
$("#prev ~ div").css("border", "3px groove blue");
});
</script>
<div>div (doesn't match since before #prev)</div>
<span id="prev">span#prev</span>
<div>div sibling</div>
<div>div sibling <div id="small">div niece</div></div>
<span>span sibling (not div)</span>
<div>div sibling</div>
Change the #prev span to a div and you'll get the same failure as you're getting currently. I'd submit a bug with the jquery team.

Categories

Resources