Why the function NodeValue__Two() show null? To me, it should show the same thing as the function NodeValue__One().
I have tested this on IE6.
<html>
<body>
<script language="JavaScript">
function NodeValue__One()
{
alert(myNodeOne.childNodes(0).nodeValue);//This is OK
}
function NodeValue__Two()
{
alert(document.all[6].nodeValue);//This is NOT OK
}
</script>
<p>This PARAGRAPH has two nodes,
<b id="myNodeOne">Node One Text</b>, and
<b id="myNodeTwo">Node Two Text</b>.
<input id="txt1" type="text" value="Damn!!!" />
</p>
<button onclick="NodeValue__One();">Node Value 1</button></br>
<button onclick="NodeValue__Two();">Node Value 2</button>
</body>
</html>
The All array is an array of Elements. Elements do not have a value in the nodeValue.
On the other hand childNodes will contain both Elements and TextNodes.
Its really hard to get the index of All correct since the number of actual elements listed in All can vary from what you are seeing in the HTML. For example dispite there being no HEAD or TITLE Element present in the HTML text, they will be present in the DOM.
Both approaches are deprecated and not safe. It would be better if you gave your elements unique identifiers and used getElementById function to find elements in the DOM:
var element = document.getElementById('id_of_element');
One reason may be that you have erroneously assumed that "This Paragraph has two nodes". It has at least six, including the three text nodes containing "This PARAGRAPH has two nodes,", ", and" and ".".
Use document.all[6].text this will give you Node Two Text
Related
Edit: Thanks for the helpful answers so far! I'm still struggling to print the input to the "right" div, though. What am I missing?
Next to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed eiether left or right on the click of a button. This is what I have - but it only prints to the left, no matter the selection.
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
</script>
Sorry if this is very basic - I am completely new to JS and jQuery.
I'm trying to print input from a form into a div. This is part of the source HTML modify (it's for a university class):
<input type="text" class="input">
<div class="left">
</div>
<div class="right">
</div>
Basically, text is entered into the field, and I need to print this text either to the "left" or the "right" div when a button is clicked.
So far, I have only ever dealt with divs that had IDs, so I used
document.getElementById("divId").innerHTML = ($('.input').val());
But what do I do now when I don't have an ID? Unfortunately, changes to the HTML source are not an option.
Thanks in advance!
Just use normal selectors, like css and jQuery does.
https://api.jquery.com/category/selectors/
in your case:
$('div.left').html($('.input').val());
As you see there are many ways to do this. You can get elements by tag name, class, id...
But the most powerful way is to get it with querySelector
function save() {
var input = document.querySelector('input').value;
document.querySelector('div.left').innerHTML = input;
}
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
There are plenty of other ways to target HTML elements, but the one you're looking for in this case is getElementsByTagName(). Note that this returns a NodeList collection of elements, so you'll additionally need to specify the index that you wish to target (starting at 0). For example, if you want to target the second <div> element, you can use document.getElementsByTagName("div")[1].
This can be seen in the following example:
let input = document.getElementsByTagName("input")[0];
let button = document.getElementsByTagName("button")[0];
let div2 = document.getElementsByTagName("div")[1];
button.addEventListener("click", function(){
div2.innerHTML = input.value;
});
<input type="text">
<button>Output</button>
<br /><br />
<div>Output:</div>
<div></div>
Since you have unique class names for each element, document.getElementsByClassName can be used. This will return an array of elements containing the class. Since you only have one element with each class name, the first element of the returned array will be your target.
<input type="text" class="input">
<button onclick="save()">Save</button>
<div class="left"></div>
<div class="right"></div>
<script>
function save() {
var input = document.getElementsByClassName('input')[0].value;
document.getElementsByClassName('left')[0].innerHTML = input;
}
</script>
This is one of the many ways to do what you want:-
Write the following in console:
document.getElementsByTagName("div");
now you can see the total number of div elements used in your current document/page.
You can select one of your choice to work on by using "index number"(as in array index) for that particular div.
Lets say your div having class name = "right" is the 3rd one among the other div elements in your document.
This will be used to access that div element.
document.getElementsByTagName("right")[2].innerHTML = "whatever you want to write";
I'm newbie to Javascript, I tried the below code, it works fine for <div> element but not for <P> and <h1> elements
<script type="text/javascript">
function PrintText(){
document.getElementById('heading').innerText = 'Hello World';
}
</script>
<body>
<div id="heading"></div> // Works
<h1 id="heading"></h1> // Not Working
<P id="heading"></P> // Not Working
<button type="button" onclick="PrintText()">Submit</button>
</body>
When I use document.getElementById('heading').innerHTML= 'Hello World'; for <P> and <h1> elements the above script works(Using innerHTML instead of innerText)
Why the innerText property is not working for <p> and <h1> elements?
First suggestion is don't ever put same IDs on multiple elements in same page.
Why?
Because when you do document.getElementById() browser lookup stops when it finds first element of that ID.
Second suggestion is:
Change
innerText
To.
textContent
innerText won't work cross browser. Better to use standard way to put text with textContent.
Problematic here is your are using IDs. An ID is something unique. An ID can't be reused. If you want to assign multiple elements at once give them the same class and call them by class in your Javascript code. This should solve your problem as Javascript does not expect multiple elements to have the same ID and so it is only editing the first element.
<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>
This is my code, how to get the content inside the paragraph tag. [The tag may change to div or ul]. I need all the content inside the paragraph tag by javascript.
The output should be :
First Text Second Text
Sorry I am new to javascript, searched but cant find answer for this relevant problem. Thanks
To get the value of a tag, you can get the element with a selector and use innerHTML to get the value. like this:
<p>hi there</p>
console.log(document.getElementsByTagName('p')[0].innerHTML);
n.b. in the code above it's selecting by tag name, so it returns an array of matching elements
So in your example, using .innerHTML with give you the P tags content, including any html tags etc.
if you want just the content, you can use .textContent
console.log(document.getElementsByTagName('p')[0].textContent);
This wont give you the inner html tags
n.b. there is also the innerText method, However this isnt supported accross browsers.
You can change according to the tag you need, but basically this will do the trick:
document.getElementsByTagName('p')[0].innerText
Fiddle
InnerText should be a good solution.
console.log(document.getElementsByTagName('p')[0].innerText);
<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
justify;line-height:normal">
First Text
<span lang="EN-US" style="font-size:12.0pt;
font-family:"Times New Roman","serif"">
Second Text</span>
</p>
Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.
<html>
<body>
<script language="javascript">
function getSelectionHTML()
{
var div = document.getElementById("myDiv");
if (document.createRange) {
var textNode=div.firstChild;
var rangeObj=document.createRange();
rangeObj.setStart(textNode,0);
rangeObj.setEnd(textNode,5);
div .innerHTML = div .innerHTML.replace(rangeObj.toString(), '<span style="background-color: lime">'+rangeObj.toString()+'</span>')
}
}
</script>
<div id="myDiv">
asdf as<b>dfas df asf asdf sdfjk dvh a sjkh jhcdjkv</b> iof scjahjkv ahsjv hdjk biud fcsvjksdhf k
</div>
<form name="aform">
<input type="button" value="Get selection" onclick="getSelectionHTML()">
</body>
</html>
Ok. Let me explain -> getSelectionHTML() method is for selection of characters from 0 to 10. I am getting the values by "myDiv" id. but inner bold, italic & other tags are giving me trouble.
In simple words, I just want to make selection of first ten characters (& apply them span tag) which are in "myDiv" tag.
What exactly I am missing?
This is much easier in IE using TextRange, which is based around characters, words and sentences rather than nodes and offsets. In non-IE browsers, you'll need to do tedious manual traversal of text nodes in the DOM. However, even if you were to do this to get the first ten text characters within your <div> (which would be "asdf asdfa"), your strategy is flawed because you're using a replacement on innerHTML, which would try and fail to find "asdf asdfa" (innerHTML would start with "asdf as<b>dfa", or possibly "asdf as<B>", depending on browser).
What I would suggest is doing the DOM traversal to find all text nodes within the <div> and surrounding the parts of the text nodes you need with <span>s, thus avoiding Ranges altogether and therefore making this work in all major browsers.
You're trying to select e.g. character 1 to 10 of your text. But when using Range.setStart and .endStart, the first parameter is the text node containing your text. If you browse through the DOM with Firebug (or Web Inspector), you'll notice that character 10 of your text resides in another element (the <b> element), with its own text node.
BTW, you left out several required elements/tags, which can also be a source of errors.
My corrected version reads
<!DOCTYPE html>
<html>
<head>
<title>Title element is required</title>
<body>
<script>
function getSelectionHTML()
{
var div = document.getElementById("myDiv");
var bEl = document.getElementById("bEl");
if (document.createRange) {.
var textNode=div.firstChild;
var rangeObj=document.createRange();
rangeObj.setStart(textNode,0);
rangeObj.setEnd(bEl.firstChild,2);
alert(rangeObj.toString());
// div.innerHTML = div.innerHTML.replace(rangeObj.toString(), '<span style="background-color: lime">'+rangeObj.toString()+'</span>');
}
}
</script>
<div id="myDiv">
asdf as<b id="bEl">dfas df asf asdf sdfjk dvh a sjkh jhcdjkv</b> iof scjahjkv ahsjv hdjk biud fcsvjksdhf k
</div>
<form name="aform">
<input type="button" value="Get selection" onclick="getSelectionHTML()">
</form>
</body>
</html>
Now rangeObj contains the selected text, but you can't simply insert a <span> element the way you tried, because elements can't be nested this way:
<span>asdf as<b>dfa</span>s df asf…