Inner Text not working for Paragraph and Heading HTML Elements - javascript

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.

Related

Get the Text inside the 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>

how to give innerhtml values to elements inside a cloned div

I am implementing a search form, for that I need divs dynamically for showing search results.
Now I am trying is,
create the html elements.
for each result, clone the structure and replace the inner html of appropreate elements with my results.
Append the result with the existing results.
but I dont know how to replace the innerhtml with the results.
I have created the following code in html,`
<div id="resultsDiv">
<div id="webResult">
<div id="heading"></div>
<p id="s_item"></p>
<h5 id="s_description"></h5>
<span id="s_offer"></span>
</div>
</div>
and for javascript I have crated,
templete_element=document.getElementById('resultsDiv');
for(i=0;i<result_count;i++){
$("#webResult").clone().insertAfter("#webResult");
}
For each execution of for loop I need to:
replace inner html of id 'heading' with dataArray.root.data.partners[0].item_heading
replace inner html of id 's_item' with dataArray.root.data.partners[0].item_name
replace inner html of id 's_description' with dataArray.root.data.partners[0].item_description
replace inner html of id 's_offer with' dataArray.root.data.partners[0].item_offer
Please forgive me If my language is bad.
thanku.
You should avoid creating elements with duplicate ids on a page, this makes it impossible to reference them as an ID has to be unique. You should change your markup to work with classes instead:
<div id="resultsDiv">
<div class="webResult">
<div class="heading"></div>
<p class="s_item"></p>
<h5 class="s_description"></h5>
<span class="s_offer"></span>
</div>
</div>
After that you can work with those classes instead:
for(i=0;i<result_count;i++){
var myResult = $(".webResult:first").clone().insertAfter(".webResult:last");
myResult.find('.heading').html( 'put dynamic data here' );
}
I used the first and last modifiers to get the first element as the "template" and append it to the last one created in the loop.

How to find active tag formats using jQuery?

I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});

Cannot get the hidden tag value

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.

JavaScript - DOM nodeValue problem

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

Categories