Replacing HTML text with javascript - javascript

I am trying to replace some html text from some code with some new text using javascript and I have learned about Javascript HTML DOM which I believe is the way to do this; however, whenever write a method, nothing seems to change.
This is a line I am interested in changing. I want to change "Text here" to "Hello World!".
Text here
This the code I used
<script> document.getElementById("login_or_create_user_modal").innerHTML = "Hello World!"; </script>
My first concern is I have noticed that it is a data-reveal-id which is not the same as the usual id, is there a better method to use in this case? I couldn't find anything relating to data-reveal-id.
The other thing I am trying to change is to change the text cart to "Hello World!'. Again, the method I used does not do anything.
<script> document.getElementById("shopping_cart_btn").innerHTML = "Hello World!"; </script>
Am I using the right ID or am I just completely in the wrong path here?
Thanks :)

for document.getElementById() to work, you need an id attribute set, try:
Text here

change your "data-reveal-id" to just "id" and it should work

You're on the wrong path but you were heading the right direction. You just need to hop tracks and climb onto the document.querySelector() train, leaving document.getElementById behind for now.
getElementById will return an element whose id attribute equals the provided value; it won't look at any other attributes, like data-reveal-id.
querySelector instead uses CSS selectors to select an element. For examples of CSS selectors, refer the W3C documentation here: http://www.w3.org/TR/selectors/#selectors
You would use this like so:
document.querySelector("[data-reveal-id='shopping_cart_btn']").innerHTML = "Hello World!";
document.querySelector("[data-reveal-id='shopping_cart_btn']") is saying "get me the first element you can find whose data-reveal-id attribute is equal to shopping_cart_btn.
Here's a working example to prove I'm not crazy. When the JavaScript runs, it selects the div by its data-reveal-id attribute, then replaces its inner HTML:
document.querySelector("[data-reveal-id='something_random']").innerHTML = "New Text";
<div data-reveal-id="something_random">Original Text</div>

Related

not able to change class within id although no errors

I don't understand why my extraInfo variable isn't being printed out onto the webpage.
The information is being retrieved correctly (I've tested this with alert()) but I just cannot figure out why it isn't replacing the span text with the returned value.
I've tried sending it out wrapped in P tags too and although no errors come out, it still doesn't amend the text.
https://github.com/ralam87/Quote-generator
Where am I going wrong?
document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo;
I gone through your example.
Note: when you are trying to assign the citation to first element with .citation class that time the there are no elements present with the class citation because it get replaced when you set the value to source element just before citation document.getElementById("source").innerHTML = author;.
This are possible solution
change this document.getElementById("source").getElementsByClassName("citation")[0] = extraInfo; to document.getElementsByClassName("citation")[0].innerHtml = extraInfo;
remove the id from <p id="source">
create another <span> or <div> or <p> element inside the existing <p> and assign the id=source to that inner element. for example <p><span id="source"></span><span id="citation"></span></p>.
If you want to have the , after the source name then at the time of assigning the document.getElementById("source").innerHTML = author + ',';.
If you allow me i can also contribute this directly to you git
repository.

Javascript innerHTML

I am currently learning Javascript DOM and innerHTML and found some problems in understanding innerHTML.
Here are my codes: http://jsfiddle.net/hphchan/bfjx1w70/1/
I have learnt standard DOM method and innerHTML methods and it works fine, BUT I don't know why it is wrong to code the following:
// this method fails
var element2 = document.createElement('p');
element2.innerHTML = "hello <em>Herbert</em>";
// standard methods of innerHTML method I learnt from textbook, BUT it requires to type tags in HTML
var element3 = document.getElementById('el');
element3.innerHTML = "innerHTML: hello <em>Herbert</em>";
I want to ask why it does not work for the first method. What is the problem of doing in this way? In addition, what if I don't want to type anything (including tags) in HTML and want to use innerText to fulfil the same output as what the JSFiddle shows "hello Herbert"?
The main error is the innerText usage. For most purposes, I would stay away from that in general, as innerHTML works for both situations. (text and markup)
Although I suppose innerText has it's charms if you want to display HTML code as it is rather than render it.
So, because you have an HTML tag inside the string, it's not a normal text node. If you simply used 'hello Herbert' instead of 'hello Herbert' it would work.
var element2 = document.getElementById('el');
element2.innerText = "hello Herbert";
<p id='el'></p>
The other problem is though you have the element, until you have actually put it in the DOM, it is useless, which is why example 2 isn't working.
Try
document.body.appendChild(element2);
So,
var element2 = document.createElement('p');
element2.innerHTML = "hello <em>Herbert</em>";
document.body.appendChild(element2);
Hope it helps! Look at http://www.w3schools.com/jsref/met_node_appendchild.asp for more info.
Because "hello <em>Herbert</em>" contains html tag (em) so innerText won't work but innerHTML work.
The text "hello <em>Herbert</em>" is not exactly a text, as it has HTML Content in it. You really need to use innerHTML for this case:
element2.innerHTML = "hello <em>Herbert</em>";
With innerText you can only apply plain Strings without formatting to an element. Useful in a dynamic function if you don't want that the text inside an element gets formatted. If it contains tags, they will be just shown as plain text. With innerHTML you can add anything to that element, including HTML-Tags.
EDIT: Now I've just seen that your problem was that the element wasn't even displaying at all, I just thought you wonder why Herbert didn't got italic. In this case it's because you didn't append the 2nd element to the body, like you did in the first version. The third version isn't creating an element, it uses an existing one, therefore you don't need to append it. ;)

Change getElementsByClassName()[i] field

I'm doing kinda learning by doing JavaScript right know, but I have a problem, where I can not find the solution on stackoverflow. I want to replace a String on a webpage, where I just have the class, but not the ID.
document.getElementsByClassName('ep_price')[0]="FOO"
This should change the defined elemet to FOO, but it does not do that and I have no idea why not...
I have read that I should use .value, but this var is not even defined...
See Screenshot of my Chrome console below:
You need to use .textContent property if you intended to change the text.
document.getElementsByClassName('ep_price')[0].textContent ="FOO"

document.write to display content on same page.

I have a doubt with javascript document.write method. Mostly when I use document.write() it shows me the content written with the method in a different page. For instance, if I write the command like this, document.write("Hello, My name is Sameeksha"); then the execution of this line takes me to a different document on the same page. I want to be able to append the message on the same page, with other elements of the page. For example, if I have text boxes and buttons on the page and I want the text with document.write to appear under all the content of the page or on a particular section of a page. Please suggest what can be done to get the output in this way? As, this way it will be really easy to create dynamic HTML content.
Thank you so much for your time.
Regards,
Sameeksha Kumari
document.write is basically never used in modern Javascript.
Whan you do instead is to create explicit DOM elements and append them to the document in the place you want. For example
var x = document.createElement("div"); // Creates a new <div> node
x.textContent = "Hello, world"; // Sets the text content
document.body.appendChild(x); // Adds to the document
Instead of appending to the end you can also add child nodes to any existing node. For example:
function addChatMessage(msg) {
var chat = document.getElementById("chat"); // finds the container
var x = document.createElement("div");
x.textContent = msg;
chat.appendChild(x);
}
I'd say 6502 posted the more correct way to do it, but I think someone should mention innerHTML as well. First, give some element in your HTML body an id so you can reference it:
<div id="outputDiv">I'm empty.</div>
Then, either at the bottom of your document (at the end of the <body> tag), or any other time after the page is loaded, you can update the contents with innerHTML:
document.getElementById("outputDiv").innerHTML = "<h1>Hello!!!</h1>";
Here's a jsfiddle demonstrating this. This isn't as clean/correct/elegant as using the more standard DOM methods, but it's well supported. Sometimes quick and dirty is what you need!

Could be jquery used to modify html strings?

I have for example such piece of html:
var html = '<p>Title</p><b>edit me</b><i>remove me</i>';
I want to change title in it, but do not want to use regexp or string replace
functions for this, because if title would match tag name, then html could be corrupted.
I now trying to adopt jQuery for this, because it seems capable, but in reality things not so easy. Here is code:
$( $(html)[0] ).text('New title');
console.log(html); // --> prints out original html with old title
Any idea how to make this code work if it is at all possible ?
html = $('<div/>').html(html).find('p').text('New title').end().html();
http://jsfiddle.net/bEUHN/
Note: There are 3 wrapper elements in the created jQuery object using $(html), for selecting the p element you should use filter method.
$(html).filter('p').text('New title');

Categories