I was writing some code the other day, and for some reason, I had no idea why this happened, but this was part of the code that I had written.
var item = document.getElementByClass('object');
var innerImageId = item.firstChild.id;
I went over this code a lot of times. The problem of this code is that the value of innerImageId is undefined. The firstChild of item is an image. I need to get the id of the image, but no matter how many times I went over the code, it did not work. Here is the HTML file of the code.
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
Doesn't this seem correct? Well, I did some debugging in Google Chrome, and it turns out that there are 3 nodes in the div "object". The id of the first and the last node was undefined, but the 2nd one was "sample-image".
I then tried "firstElementChild" instead of "firstChild", and this worked well.
Then just to test it out, I did something like this-
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
(or with multiple lines of unnecessary whitespace)
but it still shows 3 nodes, the enter symbol, the div, and another enter symbol.
This problem keeps occurring in Chrome, Internet Explorer and Firefox.
Can someone please explain why there are these random 2 extra nodes?
The browser insert a text node when there are white spaces or new lines in your code. You are targeting one of those.
Try
var img = document.querySelector('.object img');
var innerImageId = img.id;
You can also use firstElementChild in place of firstChild which will skip those empty text nodes.
EDIT: Blah thanks BAM5 just not paying attention as I typed.
There isn't a getElementByClass method, this is why you failed. Open console and you'll see JS error. I guess what you thought were getElementsByClassName. Note it's in plural form, and it returns an array-like.
Even if you get over the first issue, you may still fail due to your markup. firstChild does return the first one among children, including the text nodes. Your better choice is firstElementChild. Or you have to write like this to avoid text node children:
<div><img></div>
So, this should give what you wanted:
var items = document.getElementsByClassName('object');
var innerImageId = items[0].firstElementChild.id;
On the other hand, other answers pointed that querySelector can do the job, indeed. And it has a brother querySelectorAll. You could search MDN for their usages and slight difference in between.
Use firstElementChild instead of firstChild. As l. Catallo said, you may be getting a text node instead of an element.
Looks like Atheist beat me to it, but in his answer he incorrectly used firstChildElement. Would comment, but not enough rep...
I faced a similar question while I was learning DOM exploration and I observed that, when there is a space or the next tag is on the next line, the node list normally shows a text node. For Example:
If I wrote my HTML code as below, and tried to get all the child nodes of the element body.
HTML Code:
<body>
<h2> Lets Study DOM!! </h2>
<input type = 'text' id = 'topic'> </input></br>
<button onClick = addToList()> Click Me to Add </button>
Javascript:
console.log(document.querySelector('body').childNodes);
The above code gave me the following output:
[text, h2, text, input#topic, text, br, text, button, text, ul#unordered, text, script]
On the other hand, if I modified my code as shown below, and then tried to print the node list, I got a different output as shown below:
HTML Code:
<body><h2> Lets Study DOM!! </h2>
<input type = 'text' id = 'topic'> </input></br>
<button onClick = addToList()> Click Me to Add </button>
Javascript:
console.log(document.querySelector('body').childNodes);
The above code gave me the following output:
[h2, text, input#topic, text, br, text, button, text, ul#unordered, text, script]
So clearly, the browser considers the space after the body tag as a text node.
Just for you guys to note, of course I have read this first:
Javascript get text inside a <span> element
However, my case is not that easy, let alone because I need to do it natively, without jQuery.
Supposing we have this on an arbitrary web page:
<span id="entry1" class="entries">
<img src="http://whereyourpicis.at/pic.jpg" border="0">
++ This is the plain text we want to get from the SPAN block. ++
<span id="nested2"><a onclick="doSomething()">Action!</a></span>
</span>
I've tried anything imaginable, but I can't say any of the "solutions" I tried was a good one, since it feels like a total kludge taking the whole innerHTML and then doing some sed-style regex magic on it.
There must be a more elegant way to accomplish this, which is why I'm asking here.
BTW I've also found out that even nextSibling() cannot work here.
I am not sure this is what you need, because you didn't specify what you need to be an exact output in your example code.
If you need to literally Strip HTML from Text JavaScript
you could use function like this:
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
please check this: http://jsfiddle.net/shershen08/7fFWn/3/
If you want to get only the text nodes within an element, I think you'll need to iterate over the element's childNodes and fetch the text nodes. Here's a quick-and-dirty example of a function that will fetch only the text nodes from a given element (it also skips any text nodes that are just whitespace, since those are often added as a result of HTML formatting but don't really mean anything to a human).
This is the description of the .html() method: "Get the HTML contents of the first element in the set of matched elements." My question is what exactly is the "HTML contents" it refers to?
Lets say I have a div with content I wish to store HTML content for but also render it raw for viewing purposes. Lets say e is my Div.
$(e).html() //this returns a string with what looks like regular HTML besides the occurrence of many HTML entities.
//if i search for greater than signs:
x.text().search(">") //I get 2273 which I'm assuming is the number of occurrences.
//However if I convert the HTML to a string I seem to get different content. Why?
$(output).val(e.html().toString()); //for viewing the output markup for a div
e.html().toString().search(">") //this now gives me 317, which is a lot less HTML entities than I had before
Would I be correct in saying that the .toString() method just corrupts my HTML content? Which one do I want? Whenever I render this to a raw div I get similar results for both even though they seem vastly different. Which one do I want in order to display and save the correct output information? Any knowledge is greatly appreciated!
> will match both > and > so when you run it on an html string will match all the tags as well as uses of > in text
Hard to tell what you are comparing since you use unknown x.text()
I've looked everywhere for a technique, but I failed to find much that suited my needs.
Basically, I would like to utilize JavaScript or jQuery (probably using Ajax) to grab a div that contains a word from a page on my site.
I'm not asking anyone to code this for me, I would just like to be pointed in the right direction.
For example, let's say I have this HTML page:
<div class='findfromthis'>hello guys</div>
<div class='findfromthis'>goodbye guys</div>
<div class='findfromthis'>goodbye people</div>
I would like to display all the divs that contain the word "guys" in them.
Thank you so much in advance!!
JQuery has a contains selector that will find all elements containing specific text. Something along the lines of $("div:contains('guys')") should do the trick. Then you can use .each or .show etc to work with the selected elements.
See http://api.jquery.com/contains-selector/ for more detail.
EDIT :
The following code was deemed useful by the OP. It'll select all divs with class "findfromthis" which don't contain the phrase "guys", and remove them from the DOM:
$("div.findfromthis:not(:contains('guys'))").remove();
Give your div a class, say '.myDiv' and then via jQuery:
$('.myDiv').doSomething...
I'm not entirely sure how AJAX would play into this, but to point you in the right direction:
http://api.jquery.com/jQuery.ajax/
Your edit is an entirely different question. But you'd do the same to get the divs. In this case, you'd use 'each':
$('.findfromthis').each(function(){
// for each div you can now grab the text it contains:
DivText = $(this).text();
// now you could use a variety of different JS seach techniques to find
// your content. But one example to search for a word or word fragment would be:
if (DivText.indexOf("guys") !== -1)){
// then this div has the word 'guys' in its text somewhere
}
})
If the search term is more complex (like not wanting to find fragments) then you may want to use REGEX for the search part instead.
Again, though, not sure where AJAX would fit into this. This all can happen client-side.
As title said, i want to check wether the selected text is paragraph or belong to two different paragraph or an inline text,
I am using this java script code for getting text.
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
So need to check for selectionContents.
Thanks in advance.
I suspect this isn't quite a full answer yet so I'll edit and explain further once it's more clear, but is this something like what you're looking for? http://jsfiddle.net/UFdDY/
[ getSelectionHtml() referenced from HTML of selected text ]
EDIT:
Now take a look at the revision, it can tell the difference between inline text and an entire paragraph if this is what you're looking for, but it takes some modification to the html (assumes you're using server side script to generate the output).
http://jsfiddle.net/UFdDY/1/