Javascript:: textContent/innerText of firstChild - javascript

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];

Related

How to use javascript to find and replace a word split in a few tags?

I want to use javascript to find and replace a word which has been split in a few tags.
For example, the html code:
<html>
<body>
<div id="page-container">
This is an apple.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
</div>
</body>
</html>
And the it looks like below in the web browser:
This is an apple.
apple.
I use this javascript to find and replace the word "apple":
var a = document.getElementById('page-container').innerHTML;
a=a.replace(/apple/g,'pear');
document.getElementById('page-container').innerText=a;
But the result in the web browser is very bad, and all the tags could not work:
This is an pear.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
It seems the replace function worked for the first row but cannot recognize the word split in the tags. This is an example, the whole content could be much more complex with more tags like , , not only ... Is there a way to replace only text but keep the original html tag format?
var a = document.getElementById('page-container').textContent;
a = a.replace(/apple/g, 'pear');
var a=a.split('.');
document.getElementById('page-container').innerHTML = `${a[0]}.<br/><span> ${a[1]}
<span>`;
That is because you have nested elements, so when you set innerHTML of the parent div, it treats inner div as text and print it out , try to replace this :
document.getElementById('page-container').innerText=a;
with this :
document.getElementById("page-container").firstChild.innerHTML = a;
So, you target only your first child which is parent div.
Live example:
https://jsbin.com/hujurageya/edit?html,js,output

How can I get the HTML of an element

For example I have:
<div id="f" style="width:50px; height:50px; background-color:#ddd">
<p>Some text</p>
</div>
I want to get <div id="f" style="width:50px; height:50px; background-color:#ddd">
This is what I have tried so far:
alert(document.getElementById("f").innerHTML);
alert(document.getElementById("f").outerHTML);
and jsfiddle of it.
There is no direct way to do this. However, you could remove the innerHTML content from the outerHTML content.
document.getElementById("f").outerHTML.replace(document.getElementById("f").innerHTML,'')
The closest I can think of is to clone it, remove all contents, get outerHTML, and then remove the </div> from the end.
var clone = document.getElementById("f").cloneNode(true);
clone.innerHTML = "";
var html = clone.outerHTML.replace(/<\/div>\s*$/, '');
You almost have the solution, using outerHTML. You just want to split the returned string after the first > character, which is easy using JS .split().
For example:
var html = document.getElementById("f").outerHTML;
var part = html.split(">")[0] + ">";
So: I get the whole HTML, split it by the > character, then add the > back in (because split() removes it).
Here's an updated fiddle of it.

How to get div text value?

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.

jquery html() and append() not working

for some reason both methods results are TextNode. It means that browser doesnot parse content of appended string.
for example
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append(code);
on the page I do have content
"<div><p>Some</p> news are <span>here</span></div>"
this
$("#news_details").contents()
shows that string with html source is attached(for some reason unknown to me) as single textnode
but if will type in firebug
var text = $('#news_detaisl').text()
$('#news_details').contents().remove()
$('#news_details').append(text)
and after that, it is parsed and shows in a right way.
user the html()
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").html(code);
Since you haven't asked a question directly I can only assume what you want. Try this and tell me if it helps and if it was what you wanted:
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append($(code));
Oh and $().append and $().html do NOT behave in the same way. $().append adds the input as a new child while $().html either returns the innerHTML of an element or sets it. Depending on whether you set a parameter.
only this code works fine, but such a weird behavior
var content = news.newsDetails(here async ajax request which load html snippet with content); //content is a string with html snippet from server
$("#news_content").append(content);
var value = $(".news_title").text();
$(".news_title").contents().remove();
$(".news_title").append(value);
$(".news_details").css('display','block')
and html snippet
<div class="news_details">
<img class="pointer" src="/static/img/close6.png" alt="close" width='16' height='16'>
<div class="news_head gradient">
<span>{{ item.pub_date|date:"d M Y" }}</span>{{ item.title }}
</div>
<div class="clear"></div>
<div class="news_title">{{ item.full_text }}</div>

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.

Categories

Resources